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 BanIcon from 'assets/icons/messages/ban.svg';
import {
  usePostRemoveParticipantMutation,
  usePostSharedTripAddParticipantMutation
} from '@api/events';
import { useSafeAreaInsets } from 'react-native-safe-area-context';

const OptionsModal = () => {
  const insets = useSafeAreaInsets();
  const [userData, setUserData] = useState<any>(null);
  const { mutateAsync: removeParticipant } = usePostRemoveParticipantMutation();
  const { mutateAsync: addParticipant } = usePostSharedTripAddParticipantMutation();

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

  const handleSheetOpen = (payload: any) => {
    setUserData(payload);
  };

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

    setShouldOpenWarningModal({
      title: `Remove ${userData?.name}`,
      message: `Are you sure you want to remove ${userData?.name} as a participant?`,
      action: async () => {
        await removeParticipant(
          {
            token: userData.token,
            event_id: userData.eventId,
            user_id: userData.userId
          },
          {
            onSuccess: () => {
              userData.filterParticipants();
            }
          }
        );
      },
      buttonTitle: 'Remove',
      isWarningVisible: true
    });

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

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

    await addParticipant(
      {
        token: userData.token,
        event_id: userData.eventId,
        user_id: userData.userId
      },
      {
        onSuccess: () => {
          userData.filterParticipants();
        }
      }
    );

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

  return (
    <ActionSheet
      id="host-options-modal"
      gestureEnabled={true}
      onBeforeShow={(sheetRef) => {
        const payload = sheetRef || null;
        handleSheetOpen(payload);
      }}
      onClose={() => {
        if (shouldOpenWarningModal) {
          userData?.setIsWarningVisible(shouldOpenWarningModal);
        }
      }}
      onBeforeClose={() => SheetManager.hide('host-options-modal')}
      containerStyle={styles.sheetContainer}
      defaultOverlayOpacity={0.5}
      indicatorStyle={{ backgroundColor: 'transparent' }}
    >
      {userData && (
        <View style={[styles.container, { paddingBottom: insets.bottom + 8 }]}>
          <View style={[styles.optionsContainer, { paddingVertical: 0, gap: 0 }]}>
            <TouchableOpacity
              style={[styles.option, styles.dangerOption]}
              onPress={userData.interested ? handleAddParticipant : handleRemoveParticipant}
            >
              {userData.interested ? (
                <Text style={[styles.optionText]}>Add participant</Text>
              ) : (
                <>
                  <Text style={[styles.optionText, styles.dangerText]}>Remove participant</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 OptionsModal;
