import React, {useCallback, useState} from 'react';
import {View} from 'react-native';
import {useTranslation} from 'react-i18next';
import {
  IconLogout,
  IconUser,
  IconUserCheck,
  IconUserMinus,
} from '@tabler/icons-react-native';
import {useNavigation} from '@react-navigation/native';
import {useMutation} from '@tanstack/react-query';
import {Typography, Dialog, Button, ListRow} from '@components';
import {Membership} from '@modules/chats/interfaces';
import {
  grantAdminPermissionInConversation,
  kickUserFromConversation,
  revokeAdminPermissionInConversation,
} from '@modules/chats/services';
import {visibleChatStore} from '@modules/chats/store';
import {conversationMarker} from '@modules/chats/instances/ConversationMarker';
import {MembershipUpdaterService} from '@modules/chats/instances/updaters';
import {showChatSnackbar} from '@modules/chats/utils';
import {showSnackbar} from '@redux/dispatchers';
import {useTheme} from '@shared/theme';
import {getCompleteName, getUlid} from '@shared/utils';
import {Screens} from '@shared/constants';

import {styles} from './styles';

interface Props {
  membership: Nullable<Membership>;
  channel: string;
  isVisible: boolean;
  onClose: () => void;
}

function DialogMemberActions({membership, channel, isVisible, onClose}: Props) {
  const {t} = useTranslation();
  const {theme} = useTheme();
  const navigation = useNavigation();
  const fullName = getCompleteName({
    firstName: membership?.user.first_name || '',
    lastName: membership?.user.last_name || '',
  });
  const [showDeleteConfirmation, setShowDeleteConfirmation] = useState(false);

  const onCloseHandler = useCallback(() => {
    onClose();
    setShowDeleteConfirmation(false);
  }, [onClose]);

  const {mutate: kickUserMutate} = useMutation({
    mutationFn: kickUserFromConversation,
    onSuccess: async data => {
      await MembershipUpdaterService.deleteUserGroupMembership(
        Number(data.membership.user.id),
        channel,
      );
      onCloseHandler();
      visibleChatStore.getState().getGroupInfo(channel);
      conversationMarker.markConversationAsRead(channel);
    },
    onError: () => {
      onCloseHandler();
      showSnackbar({
        variant: 'error',
        title: t('errors.api.500', {info: ''}),
      });
    },
  });

  const {mutate: revokeAdminMutate} = useMutation({
    mutationFn: revokeAdminPermissionInConversation,
    onSuccess: async data => {
      await MembershipUpdaterService.saveGroupMemberships({
        channelId: channel,
        memberships: [
          {
            conversation_id: channel,
            is_admin: false,
            version: data.membership.version,
            user_id: Number(data.membership.user.id),
          },
        ],
      });
      onCloseHandler();
      showChatSnackbar({
        variant: 'success',
        title: t('chat.groups.manage.revoke_admin_success', {
          user: fullName,
        }),
      });
      visibleChatStore.getState().getGroupInfo(channel);
    },
    onError: () => {
      onCloseHandler();
      showChatSnackbar({
        variant: 'error',
        title: t('errors.api.500', {info: ''}),
      });
    },
  });

  const {mutate: grantAdminMutate} = useMutation({
    mutationFn: grantAdminPermissionInConversation,
    onSuccess: async data => {
      await MembershipUpdaterService.saveGroupMemberships({
        channelId: channel,
        memberships: [
          {
            conversation_id: channel,
            is_admin: true,
            version: data.membership.version,
            user_id: Number(data.membership.user.id),
          },
        ],
      });
      onCloseHandler();
      showChatSnackbar({
        variant: 'success',
        title: t('chat.groups.manage.assign_admin_success', {
          user: fullName,
        }),
      });
      visibleChatStore.getState().getGroupInfo(channel);
    },
    onError: () => {
      onCloseHandler();
      showChatSnackbar({
        variant: 'error',
        title: t('errors.api.500', {info: ''}),
      });
    },
  });

  const onRevokeAdminPress = () => {
    if (!membership) {
      return;
    }
    revokeAdminMutate({
      channel,
      user: String(membership.user.id),
      idempotencyKey: getUlid(),
    });
  };

  const onGrantAdminPress = () => {
    if (!membership) {
      return;
    }
    grantAdminMutate({
      channel,
      user: String(membership.user.id),
      idempotencyKey: getUlid(),
    });
  };

  const goToProfile = () => {
    if (!membership) {
      return;
    }
    onCloseHandler();
    navigation.navigate(Screens.PROFILE, {userId: membership.user.id});
  };

  const deleteFromGroup = () => {
    setShowDeleteConfirmation(true);
  };

  const onConfirmDeletion = () => {
    if (!membership) {
      return;
    }
    kickUserMutate({
      channel,
      user: String(membership.user.id),
      idempotencyKey: getUlid(),
    });
  };

  return (
    <Dialog
      isVisible={isVisible}
      onClose={onCloseHandler}
      title={fullName}
      withCloseButton
      stackBehavior="replace">
      <View style={styles.container}>
        {showDeleteConfirmation ? (
          <>
            <View style={styles.confirmationContainer}>
              <Typography weight="semiBold" align="center">
                {t('chat.groups.manage.delete_from_group_title', {
                  user: fullName,
                })}
              </Typography>
              <Typography>
                {t('chat.groups.manage.delete_from_group_description')}
              </Typography>
            </View>
            <View
              style={[
                styles.buttonContainer,
                {borderColor: theme.border.neutral.default},
              ]}>
              <Button
                onPress={onConfirmDeletion}
                text={t('general.delete')}
                variant={'primary'}
              />
              <Button
                onPress={onCloseHandler}
                text={t('general.cancel')}
                variant="tertiary"
              />
            </View>
          </>
        ) : (
          <View style={styles.buttonsContainer}>
            <ListRow
              onPress={
                membership?.is_admin ? onRevokeAdminPress : onGrantAdminPress
              }>
              <ListRow.Avatar
                Icon={membership?.is_admin ? IconUserMinus : IconUserCheck}
              />
              <ListRow.Title
                title={t(
                  membership?.is_admin
                    ? 'chat.groups.manage.remove_admin_modal'
                    : 'chat.groups.manage.assign_admin_modal',
                )}
              />
            </ListRow>
            <ListRow onPress={goToProfile}>
              <ListRow.Avatar Icon={IconUser} />
              <ListRow.Title title={t('chat.go_to_profile')} />
            </ListRow>
            <ListRow onPress={deleteFromGroup}>
              <ListRow.Avatar Icon={IconLogout} variant="error" />
              <ListRow.Title
                title={t('chat.groups.manage.delete_from_group')}
              />
            </ListRow>
          </View>
        )}
      </View>
    </Dialog>
  );
}

export default DialogMemberActions;
