import ReactModal from 'react-native-modal';
import { ScrollView, Text, TouchableOpacity, View, Image } from 'react-native';
import { API_HOST } from 'src/constants';
import { useState, useEffect, useCallback } from 'react';
import { styles } from './styles';

import CheckSvg from 'assets/icons/travels-screens/circle-check.svg';
import { Colors } from 'src/theme';

const MultiSelectorCountries = ({
  isVisible,
  onClose,
  onSelect,
  data,
  initialSelectedIds = []
}: {
  isVisible: boolean;
  onClose: () => void;
  onSelect: (
    selectedItems: { country: number; name: string; count: number; flag: string | null }[]
  ) => void;
  data: { country: number; name: string; count: number; flag: string | null }[];
  initialSelectedIds?: number[];
}) => {
  const [selectedIds, setSelectedIds] = useState<number[]>(initialSelectedIds);

  useEffect(() => {
    if (isVisible) {
      setSelectedIds(initialSelectedIds);
    }
  }, [isVisible]);

  const toggleSelection = (item: {
    country: number;
    name: string;
    count: number;
    flag: string | null;
  }) => {
    setSelectedIds((prev) => {
      if (prev.includes(item.country)) {
        return prev.filter((id) => id !== item.country);
      } else {
        return [...prev, item.country];
      }
    });
  };

  const handleClose = () => {
    const selectedItems = data.filter((item) => selectedIds.includes(item.country));
    onSelect(selectedItems);
    onClose();
  };

  const isSelected = useCallback((id: number) => selectedIds.includes(id), [selectedIds]);

  return (
    <ReactModal
      isVisible={isVisible}
      onBackdropPress={handleClose}
      style={styles.modal}
      statusBarTranslucent={true}
      presentationStyle="overFullScreen"
    >
      <View style={styles.wrapper}>
        <ScrollView style={{ paddingBottom: 16 }} showsVerticalScrollIndicator={false}>
          {data?.map((item) => (
            <TouchableOpacity
              key={item.country}
              style={[styles.btnOption]}
              onPress={() => toggleSelection(item)}
            >
              <View style={styles.row}>
                <Image source={{ uri: `${API_HOST}${item.flag}` }} style={styles.flag} />
                <Text style={[styles.btnOptionText]}>{item.name}</Text>
                <Text style={[styles.btnOptionText]}>({item.count})</Text>
              </View>
              <View style={styles.unselectedCircle}>
                {isSelected(item.country) && (
                  <CheckSvg fill={Colors.DARK_BLUE} height={20} width={20} />
                )}
              </View>
            </TouchableOpacity>
          ))}
        </ScrollView>
      </View>
    </ReactModal>
  );
};

export default MultiSelectorCountries;
