import React, {Fragment, memo, useState} from 'react';
import {View} from 'react-native';
import {useTranslation} from 'react-i18next';
import {
  IconBell,
  IconBellOff,
  IconLogout,
  IconUser,
} from '@tabler/icons-react-native';
import {useNavigation} from '@react-navigation/native';
import {
  CardContainer,
  Dialog,
  Divider,
  ListRow,
  Pressable,
  Typography,
} from '@components';
import {ChatNotificationType} from '@modules/chats/interfaces';
import {ChatMuteOption, MUTE_OPTIONS} from '@modules/chats/constants';
import {useConversationActions} from '@modules/chats/hooks';
import {useMoreOptions} from '@modules/chats/store';
import {isCurrentUserTheOnlyAdmin} from '@modules/chats/db';
import {
  LeaveGroupConfirmation,
  OnlyAdminWarning,
} from '@modules/chats/components';
import {Screens} from '@shared/constants';

import {styles} from './styles';

function DialogChatItemOptionsCmp() {
  const {t} = useTranslation();
  const navigation = useNavigation();
  const [currentContent, setCurrentContent] = useState<
    'init' | 'mute' | 'onlyAdminWarning' | 'leaveGroupConfirmation'
  >('init');
  const {changeNotificationType} = useConversationActions();
  const {isVisible, target, hide} = useMoreOptions();
  const isMuted =
    target?.properties?.notification_status?.notification_type !==
    ChatNotificationType.All;
  const isGroup = target?.is_channel;
  const isInitContent = currentContent === 'init';
  const isMuteContent = currentContent === 'mute';
  const isOnlyAdminWarningContent = currentContent === 'onlyAdminWarning';
  const isLeaveGroupConfirmationContent =
    currentContent === 'leaveGroupConfirmation';
  const dialogTitle = isInitContent
    ? t('general.options')
    : isMuteContent
    ? t('chat.mute.dialog.title')
    : isOnlyAdminWarningContent
    ? t('chat.groups.manage.assign_admin')
    : isLeaveGroupConfirmationContent
    ? t('chat.groups.leave_group_question', {
        name: target?.name || '',
      })
    : '';

  const closeModal = () => {
    hide();
    // Wait for the animation to finish to avoid flickering content
    setTimeout(() => {
      setCurrentContent('init');
    }, 200);
  };

  const muteOptions = MUTE_OPTIONS.map(option => ({
    label: t(`chat.mute.dialog.options.${option}`),
    value: option,
  }));

  const showMuteContent = () => {
    setCurrentContent('mute');
  };

  const onMuteOptionPress = (option: ChatMuteOption) => () => {
    changeNotificationType({
      channel: target?.id || '',
      type: ChatNotificationType.Mentions,
      time: option,
    });
    closeModal();
  };

  const onUnmutePress = () => {
    changeNotificationType({
      channel: target?.id || '',
      type: ChatNotificationType.All,
    });
    closeModal();
  };

  const onLeaveGroupPress = async () => {
    try {
      if (!target?.id) return;

      const isOnlyAdmin = await isCurrentUserTheOnlyAdmin(target.id);
      if (isOnlyAdmin) {
        setCurrentContent('onlyAdminWarning');
      } else {
        setCurrentContent('leaveGroupConfirmation');
      }
    } catch (error) {
      // Ignore error
    }
  };

  const onGoToProfilePress = () => {
    closeModal();

    // This is to avoid delay on close modal, since next screen blocks the JS thread
    setTimeout(() => {
      if (target?.other_user?.id) {
        navigation.navigate(Screens.PROFILE, {
          userId: target.other_user.id,
        });
      }
    }, 0);
  };

  return (
    <Dialog
      isVisible={isVisible}
      onClose={closeModal}
      title={dialogTitle}
      titleNumberOfLines={2}>
      {isInitContent ? (
        <View style={styles.optionsContainer}>
          {isMuted ? (
            <ListRow onPress={onUnmutePress}>
              <ListRow.Avatar Icon={IconBell} variant="default" size="md" />
              <ListRow.Title title={t('chat.mute.unmute')} />
            </ListRow>
          ) : (
            <ListRow onPress={showMuteContent}>
              <ListRow.Avatar Icon={IconBellOff} variant="default" size="md" />
              <ListRow.Title title={t('chat.mute.mute')} />
            </ListRow>
          )}
          {isGroup ? (
            <ListRow onPress={onLeaveGroupPress}>
              <ListRow.Avatar Icon={IconLogout} variant="error" size="md" />
              <ListRow.Title title={t('chat.groups.leave_group')} />
            </ListRow>
          ) : (
            <ListRow onPress={onGoToProfilePress}>
              <ListRow.Avatar Icon={IconUser} variant="default" size="md" />
              <ListRow.Title title={t('chat.go_to_profile')} />
            </ListRow>
          )}
        </View>
      ) : isMuteContent ? (
        <View>
          <Typography>{t('chat.mute.dialog.description')}</Typography>
          <CardContainer style={styles.muteOptionsContainer}>
            {muteOptions.map((option, index) => (
              <Fragment key={option.value}>
                <Pressable onPress={onMuteOptionPress(option.value)}>
                  <Typography variant="xs" weight="semiBold">
                    {option.label}
                  </Typography>
                </Pressable>
                {index !== muteOptions.length - 1 && <Divider />}
              </Fragment>
            ))}
          </CardContainer>
        </View>
      ) : isOnlyAdminWarningContent ? (
        <OnlyAdminWarning onClose={closeModal} />
      ) : isLeaveGroupConfirmationContent ? (
        <LeaveGroupConfirmation
          channel={target?.id || ''}
          onCancel={closeModal}
          onSuccess={closeModal}
        />
      ) : null}
    </Dialog>
  );
}

export const DialogChatOptions = memo(DialogChatItemOptionsCmp);
