import React, { useState } from 'react';
import { View, Text, StyleSheet, TouchableOpacity } from 'react-native';
import ActionSheet, { SheetManager } from 'react-native-actions-sheet';
import { Colors } from 'src/theme';
import { getFontSize } from 'src/utils';
import { ChatProps } from '../types';
import { useNavigation } from '@react-navigation/native';
import { NAVIGATION_PAGES } from 'src/types';
import { usePostRemoveFromGroupMutation, usePostSetGroupAdminMutation } from '@api/chat';
import BanIcon from 'assets/icons/messages/ban.svg';
import UserTieIcon from 'assets/icons/messages/user-tie.svg';
import RemoveUserTieIcon from 'assets/icons/messages/crossed-user-tie.svg';
import UserIcon from 'assets/icons/messages/user-solid.svg';
import { useSafeAreaInsets } from 'react-native-safe-area-context';

const UserOptionsModal = () => {
  const insets = useSafeAreaInsets();

  const [userData, setUserData] = useState<any>(null);
  const { mutateAsync: setAdmin } = usePostSetGroupAdminMutation();
  const { mutateAsync: removeFromGroup } = usePostRemoveFromGroupMutation();

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

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

  const handleChangeAdmin = async () => {
    if (!userData) return;

    await setAdmin(
      {
        token: userData.token,
        value: userData.admin === 1 ? 0 : 1,
        group_token: userData.groupToken,
        uid: userData.uid
      },
      {
        onSuccess: () => {
          setUserData({ ...userData, admin: userData.admin === 1 ? 0 : 1 });
        }
      }
    );

    userData.refetchMembers();
  };

  const handleRemoveFromGroup = async () => {
    if (!userData) return;

    setShouldOpenWarningModal({
      title: `Remove ${userData?.name}`,
      message: `Are you sure you want to remove ${userData?.name} from group chat?`,
      action: async () => {
        userData.groupToken &&
          (await removeFromGroup({
            token: userData.token,
            group_token: userData.groupToken,
            uid: userData.uid
          }));

        userData.refetch();
        userData.refetchMembers();
      },
      buttonTitle: 'Remove',
      isWarningVisible: true
    });

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

  return (
    <ActionSheet
      id="user-options-modal"
      gestureEnabled={true}
      onBeforeShow={(sheetRef) => {
        const payload = sheetRef || null;
        handleSheetOpen(payload);
      }}
      onClose={() => {
        if (shouldOpenWarningModal) {
          userData?.setIsWarningVisible(shouldOpenWarningModal);
        }
      }}
      onBeforeClose={() => SheetManager.hide('user-options-modal')}
      containerStyle={styles.sheetContainer}
      defaultOverlayOpacity={0.5}
      indicatorStyle={{ backgroundColor: 'transparent' }}
      safeAreaInsets={{ top: insets.top, bottom: insets.bottom || 24, left: 0, right: 0 }}
    >
      {userData && (
        <View style={[styles.container, { paddingBottom: 8 }]}>
          <View style={styles.optionsContainer}>
            <TouchableOpacity style={styles.option} onPress={handleChangeAdmin}>
              <Text style={styles.optionText}>
                {userData.admin === 1 ? 'Dismiss as admin' : 'Make group chat admin'}
              </Text>
              {userData.admin === 1 ? (
                <RemoveUserTieIcon fill={Colors.DARK_BLUE} width={20} />
              ) : (
                <UserTieIcon fill={Colors.DARK_BLUE} width={20} />
              )}
            </TouchableOpacity>
          </View>

          <View style={[styles.optionsContainer, { paddingVertical: 0, gap: 0 }]}>
            <TouchableOpacity
              style={[styles.option, styles.dangerOption]}
              onPress={handleRemoveFromGroup}
            >
              <Text style={[styles.optionText, styles.dangerText]}>Remove from group chat</Text>
              <BanIcon fill={Colors.RED} />
            </TouchableOpacity>
          </View>
        </View>
      )}
    </ActionSheet>
  );
};

const styles = StyleSheet.create({
  sheetContainer: {
    borderTopLeftRadius: 15,
    borderTopRightRadius: 15
  },
  container: {
    backgroundColor: 'white',
    paddingHorizontal: 16,
    paddingTop: 8,
    gap: 16
  },
  optionsContainer: {
    paddingVertical: 10,
    paddingHorizontal: 8,
    gap: 8,
    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 UserOptionsModal;
