import React, { useState } from 'react';
import { View, Text, Image, StyleSheet, TouchableOpacity } from 'react-native';
import ActionSheet, { SheetManager } from 'react-native-actions-sheet';
import { Colors } from 'src/theme';
import { API_HOST } from 'src/constants';
import { getFontSize } from 'src/utils';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { ChatProps, WarningProps } from '../types';
import { useNavigation } from '@react-navigation/native';
import { NAVIGATION_PAGES } from 'src/types';
import {
  usePostDeleteChatMutation,
  usePostSetBlockMutation,
  usePostSetMuteMutation
} from '@api/chat';
import { useChatStore } from 'src/stores/chatStore';
import TrashIcon from 'assets/icons/travels-screens/trash-solid.svg';
import BanIcon from 'assets/icons/messages/ban.svg';
import BellSlashIcon from 'assets/icons/messages/bell-slash.svg';
import { AvatarWithInitials } from 'src/components';

const MoreModal = () => {
  const insets = useSafeAreaInsets();
  const navigation = useNavigation();
  const { setIsWarningModalVisible } = useChatStore();

  const [chatData, setChatData] = useState<
    | (ChatProps & {
        token: string;
        refetch: () => void;
        refetchBlocked: () => void;
      })
    | null
  >(null);
  const { mutateAsync: muteUser } = usePostSetMuteMutation();
  const { mutateAsync: blockUser } = usePostSetBlockMutation();
  const { mutateAsync: deleteChat } = usePostDeleteChatMutation();

  const [shouldOpenWarningModal, setShouldOpenWarningModal] = useState<WarningProps | null>(null);

  const handleSheetOpen = (
    payload:
      | (ChatProps & {
          token: string;
          refetch: () => void;
          refetchBlocked: () => void;
        })
      | null
  ) => {
    setChatData(payload);
  };

  const handleMute = async () => {
    if (!chatData) return;

    await muteUser(
      {
        token: chatData.token,
        value: chatData.muted === 1 ? 0 : 1,
        conversation_with_user: chatData.uid
      },
      {
        onSuccess: () => {
          setChatData({ ...chatData, muted: chatData.muted === 1 ? 0 : 1 });
        }
      }
    );
    chatData.refetch();
  };

  const handleBlock = async () => {
    if (!chatData) return;

    setShouldOpenWarningModal({
      title: 'Block user',
      buttonTitle: 'Block',
      message: `Are you sure you want to block ${chatData?.name}?\nThis user will be blocked and you will not be able to send or receive messages from him/her.`,
      action: async () => {
        await blockUser({
          token: chatData.token,
          value: 1,
          conversation_with_user: chatData.uid
        });

        chatData.refetch();
        chatData.refetchBlocked();
      }
    });

    setTimeout(() => {
      SheetManager.hide('more-modal');
      setShouldOpenWarningModal(null);
    }, 300);
  };

  const handleDelete = async () => {
    if (!chatData) return;

    setShouldOpenWarningModal({
      title: 'Delete conversation',
      message: `Are you sure you want to delete conversation with ${chatData?.name}?\nThis conversation will be deleted for both sides.`,
      action: async () => {
        await deleteChat({
          token: chatData.token,
          conversation_with_user: chatData.uid
        });

        chatData.refetch();
      }
    });

    setTimeout(() => {
      SheetManager.hide('more-modal');
      setShouldOpenWarningModal(null);
    }, 300);
  };

  return (
    <ActionSheet
      id="more-modal"
      gestureEnabled={true}
      onBeforeShow={(sheetRef) => {
        const payload = sheetRef || null;
        handleSheetOpen(payload);
      }}
      onClose={() => {
        if (shouldOpenWarningModal) {
          setIsWarningModalVisible(shouldOpenWarningModal);
        }
      }}
      containerStyle={styles.sheetContainer}
      defaultOverlayOpacity={0.5}
      indicatorStyle={{ backgroundColor: 'transparent' }}
    >
      {chatData && (
        <View style={[styles.container, { paddingBottom: 8 + insets.bottom }]}>
          <TouchableOpacity
            style={styles.header}
            onPress={() => {
              SheetManager.hide('more-modal');
              navigation.navigate(
                ...([NAVIGATION_PAGES.PUBLIC_PROFILE_VIEW, { userId: chatData.uid }] as never)
              );
            }}
          >
            {chatData?.avatar ? (
              <Image source={{ uri: API_HOST + chatData.avatar }} style={styles.avatar} />
            ) : (
              <AvatarWithInitials
                text={
                  chatData.name
                    .split(/ (.+)/)
                    .map((n) => n[0])
                    .join('') ?? ''
                }
                flag={API_HOST + 'flag.png'}
                size={32}
                fontSize={12}
              />
            )}
            <Text style={styles.name}>{chatData.name}</Text>
          </TouchableOpacity>

          <View style={styles.optionsContainer}>
            <TouchableOpacity style={styles.option} onPress={handleMute}>
              <Text style={styles.optionText}>{chatData.muted === 1 ? 'Unmute' : 'Mute'}</Text>
              <BellSlashIcon fill={Colors.DARK_BLUE} />
            </TouchableOpacity>
          </View>

          <View style={[styles.optionsContainer, { paddingVertical: 0, gap: 0 }]}>
            <TouchableOpacity style={[styles.option, styles.dangerOption]} onPress={handleBlock}>
              <Text style={[styles.optionText, styles.dangerText]}>Block {chatData.name}</Text>
              <BanIcon fill={Colors.RED} />
            </TouchableOpacity>

            <TouchableOpacity style={[styles.option, styles.dangerOption]} onPress={handleDelete}>
              <Text style={[styles.optionText, styles.dangerText]}>Delete chat</Text>
              <TrashIcon fill={Colors.RED} width={18} height={18} />
            </TouchableOpacity>
          </View>
        </View>
      )}
    </ActionSheet>
  );
};

const styles = StyleSheet.create({
  sheetContainer: {
    borderTopLeftRadius: 15,
    borderTopRightRadius: 15
  },
  container: {
    backgroundColor: 'white',
    paddingHorizontal: 16,
    paddingTop: 8,
    gap: 16
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    borderBottomWidth: 1,
    borderBottomColor: Colors.FILL_LIGHT,
    gap: 8
  },
  avatar: {
    width: 32,
    height: 32,
    borderRadius: 16,
    borderWidth: 1,
    borderColor: Colors.FILL_LIGHT
  },
  name: {
    fontSize: getFontSize(14),
    fontFamily: 'montserrat-700',
    color: Colors.DARK_BLUE
  },
  optionsContainer: {
    paddingVertical: 10,
    paddingHorizontal: 8,
    gap: 16,
    borderRadius: 8,
    backgroundColor: Colors.FILL_LIGHT
  },
  option: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between'
  },
  optionText: {
    fontSize: getFontSize(12),
    fontWeight: '600',
    color: Colors.DARK_BLUE
  },
  dangerOption: {
    paddingVertical: 10,
    borderBottomWidth: 1,
    borderBlockColor: Colors.WHITE
  },
  dangerText: {
    color: Colors.RED
  }
});

export default MoreModal;
