import React, { FC, useCallback, useEffect, useState } from 'react';
import { FlatList as List, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { Input } from '../Input';
import { styles } from './styles';
import { Item, ItemData, RegionsData } from './item';
import { useGetRegionsWithFlagQuery } from '@api/regions';
import { useFocusEffect } from '@react-navigation/native';
import { Loading } from '../Loading';
import { FlashList } from '@shopify/flash-list';

type Props = {
  itemObject: (object: any) => void;
  initialData?: ItemData[] | string[];
  date?: boolean;
  countries?: boolean;
  filteredRegions?: RegionsData[];
};

//TODO: rework to generic types + custom props

export const FlatList: FC<Props> = ({
  itemObject,
  initialData,
  date,
  countries,
  filteredRegions
}) => {
  const [selectedObject, setSelectedObject] = useState<{ name: string; id: number } | string>();
  const [search, setSearch] = useState('');
  const [filteredData, setFilteredData] = useState<ItemData[] | string[]>([]);
  const [masterData, setMasterData] = useState<ItemData[] | string[]>([]);
  const [loading, setLoading] = useState<boolean>(true);

  const { data } = useGetRegionsWithFlagQuery(filteredRegions ? false : true);

  useFocusEffect(
    useCallback(() => {
      if (filteredRegions) {
        setFilteredData(filteredRegions ?? []);
        setMasterData(filteredRegions ?? []);
        setLoading(false);

        return;
      }
      const dataToUse = initialData || data?.data;
      if (dataToUse) {
        setFilteredData(dataToUse);
        setMasterData(dataToUse);
      }
      setLoading(false);
    }, [data, initialData, filteredRegions])
  );

  if (loading) return <Loading />;

  const selectItem = (object: { name: string; id: number } | string) => {
    itemObject(object);
    setSelectedObject(object);
  };

  const searchFilter = (text: string) => {
    if (text) {
      const newData = masterData.filter((item: any) => {
        const itemData = item.name ? item.name.toLowerCase() : ''.toLowerCase();
        const initialData = item.country ? item.country.toLowerCase() : ''.toLowerCase();
        const textData = text.toLowerCase();
        return itemData.indexOf(textData) > -1 || initialData.indexOf(textData) > -1;
      });
      setFilteredData(newData as string[] | ItemData[]);
      setSearch(text);
    } else {
      setFilteredData(masterData);
      setSearch(text);
    }
  };

  const renderItem = ({ item }: { item: ItemData }) => {
    const selected = date
      ? item === selectedObject
      : item?.id === (selectedObject as { name: string; id: number })?.id;
    const backgroundColor = selected ? '#FAFAFA' : 'white';

    return (
      <Item
        selected={selected}
        item={item}
        onPress={() => selectItem(item as string | { name: string; id: number })}
        backgroundColor={backgroundColor}
        initial={initialData ? true : false}
        date={date}
        countries={countries}
        isRegionFromTrips={!!filteredRegions}
      />
    );
  };

  return (
    <SafeAreaView style={styles.container}>
      {!date && (
        <View style={{ marginTop: 12 }}>
          <Input
            inputMode={'search'}
            placeholder={'Search'}
            onChange={(text) => searchFilter(text)}
            value={search}
          />
        </View>
      )}
      <FlashList
        viewabilityConfig={{
          waitForInteraction: true,
          itemVisiblePercentThreshold: 50,
          minimumViewTime: 1000
        }}
        data={filteredData as ItemData[]}
        renderItem={renderItem}
        keyExtractor={(item) => (date ? item.toString() : item.id.toString())}
        extraData={selectedObject}
        showsVerticalScrollIndicator={false}
      />
    </SafeAreaView>
  );
};
