import React, { useCallback, useEffect, useState } from 'react';
import { View, Text, TouchableOpacity, FlatList } from 'react-native';
import { useFocusEffect, useNavigation } from '@react-navigation/native';

import {
  PageWrapper,
  Header,
  Modal,
  FlatList as List,
  WarningModal,
  Loading
} from 'src/components';
import { StoreType, storage } from 'src/storage';
import { NAVIGATION_PAGES } from 'src/types';
import { styles } from './styles';
import FixerItem from '../Components/FixerItem';
import { RateModal } from '../Components';
import { useGetCountriesQuery, useGetFixersQuery, usePostSaveRatingMutation } from '@api/fixers';

import ChevronIcon from '../../../../../assets/icons/travels-screens/chevron-bottom.svg';
import AddIcon from '../../../../../assets/icons/travels-screens/circle-plus.svg';
import InfoIcon from '../../../../../assets/icons/info-solid.svg';

const FixersScreen = ({ route }: { route: any }) => {
  const token = storage.get('token', StoreType.STRING) as string;
  const navigation = useNavigation();
  const { data: countries } = useGetCountriesQuery(token, true);
  const [selectedCountry, setSelectedCountry] = useState<{
    id: number;
    country: string;
    flag: string;
  } | null>(null);
  const { data, refetch } = useGetFixersQuery(
    token,
    selectedCountry?.id as number,
    selectedCountry ? true : false
  );
  const [isCountryPickerVisible, setCountryPickerVisible] = useState(false);
  const [fixers, setFixers] = useState<any[]>([]);
  const [isWarningModalVisible, setIsWarningModalVisible] = useState(false);
  const [selectedFixer, setSelectedFixer] = useState<any | null>(null);
  const { mutateAsync: saveRating } = usePostSaveRatingMutation();

  useFocusEffect(
    useCallback(() => {
      const fetchData = async () => {
        try {
          await refetch();
          navigation.setParams({ saved: false } as never);
        } catch (error) {
          console.error(error);
        }
      };

      if (route.params?.saved) {
        fetchData();
      }
    }, [route.params])
  );

  useEffect(() => {
    if (countries && countries.data) {
      setSelectedCountry(countries?.data[0]);
    }
  }, [countries]);

  useEffect(() => {
    if (data) {
      const sortedFixers = data.data.sort((a, b) => {
        if (b.year !== a.year) {
          return b.year - a.year;
        }
        return b.month - a.month;
      });
      setFixers(sortedFixers);
    }
  }, [data]);

  const onAddNewFixerPress = useCallback(() => {
    navigation.navigate(NAVIGATION_PAGES.ADD_FIXER as never);
  }, [navigation]);

  if (!selectedCountry) return <Loading />;

  const renderItem = ({ item }: { item: any }) => (
    <FixerItem
      item={item}
      setSelectedFixer={setSelectedFixer}
      country={selectedCountry}
      setIsWarningModalVisible={setIsWarningModalVisible}
    />
  );

  const handleSaveRating = async (values: any) => {
    const { rating1, rating2, rating3, comment } = values;
    await saveRating({
      token,
      fixer_id: selectedFixer.id,
      rating1,
      rating2,
      rating3,
      comment
    });
    setSelectedFixer(null);
    refetch();
  };

  return (
    <PageWrapper>
      <Header
        label="Fixers"
        rightElement={
          <TouchableOpacity
            onPress={() => navigation.navigate(NAVIGATION_PAGES.FIXERS_INFO as never)}
            style={{ width: 30 }}
          >
            <InfoIcon />
          </TouchableOpacity>
        }
      />
      <View style={styles.tabContainer}>
        <TouchableOpacity style={styles.countrySelector} onPress={() => setCountryPickerVisible(true)}>
          <Text style={[styles.countryText]}>{selectedCountry.country}</Text>
          <ChevronIcon />
        </TouchableOpacity>
        <TouchableOpacity style={styles.addNewTab} onPress={onAddNewFixerPress}>
          <AddIcon />
          <Text style={styles.addNewTabText}>Add New Fixer</Text>
        </TouchableOpacity>
      </View>

      <FlatList
        data={fixers}
        renderItem={renderItem}
        keyExtractor={(item, index) => item.id.toString() + index.toString()}
        style={styles.fixersList}
        contentContainerStyle={styles.fixersListContentContainer}
        showsVerticalScrollIndicator={false}
      />

      <Modal
        onRequestClose={() => setCountryPickerVisible(false)}
        headerTitle={'Select Country'}
        visible={isCountryPickerVisible}
      >
        <List
          itemObject={(object) => {
            setSelectedCountry(object);
            setCountryPickerVisible(false);
          }}
          initialData={countries?.data}
          countries={true}
        />
      </Modal>

      <WarningModal
        type={'success'}
        isVisible={isWarningModalVisible}
        onClose={() => {
          setIsWarningModalVisible(false);
        }}
        message="You can rate a fixer only once every 12 months."
      />

      <RateModal
        selectedFixer={selectedFixer}
        setSelectedFixer={setSelectedFixer}
        saveRating={handleSaveRating}
      />
    </PageWrapper>
  );
};

export default FixersScreen;
