import React, { useCallback, useEffect, useState } from 'react';
import { View, Text, TouchableOpacity, FlatList, Platform } from 'react-native';
import * as Progress from 'react-native-progress';
import { useFocusEffect, useNavigation } from '@react-navigation/native';
import moment from 'moment';

import { EditNmModal, Header, Input, PageWrapper } from 'src/components';
import { CustomButton } from '../Components';
import { NmRegionItem } from '../Components/MyRegionsItems/NmRegionItem';
import { RegionItem } from '../Components/MyRegionsItems/RegionItem';
import MegaregionsModal from '../Components/MegaregionsModal';

import { StoreType, storage } from 'src/storage';
import { NmRegion, TCCRegion } from '../utils/types';
import { Colors } from 'src/theme';
import { styles } from './styles';
import {
  useGetMegaregionsQuery,
  useGetRegionsQuery,
  usePostSetTCCRegionMutation
} from '@api/myRegions';
import { qualityOptions } from '../utils/constants';

import ChevronIcon from 'assets/icons/travels-screens/down-arrow.svg';
import { NAVIGATION_PAGES } from 'src/types';
import { useRegion } from 'src/contexts/RegionContext';
import SearchIcon from 'assets/icons/search.svg';
import { useGetListCountriesQuery } from '@api/countries';

const RegionsScreen = () => {
  const token = storage.get('token', StoreType.STRING) as string;
  const { data: megaregions } = useGetMegaregionsQuery(String(token), true);
  const { data: countriesList } = useGetListCountriesQuery(true);
  const [megaSelectorVisible, setMegaSelectorVisible] = useState(false);
  const [countrySelectorVisible, setCountrySelectorVisible] = useState(false);
  const [selectedMega, setSelectedMega] = useState<{ name: string; id: number | 'all' }>({
    id: 'all',
    name: 'ALL MEGAREGIONS'
  });
  const [selectedCountry, setSelectedCountry] = useState<{ name: string; id: number } | null>(null);
  const { data: regionsQe } = useGetRegionsQuery(
    selectedCountry ? undefined : selectedMega.id,
    selectedCountry ? selectedCountry.id : undefined,
    String(token),
    true
  );
  const [total, setTotal] = useState(0);
  const [isEditModalVisible, setIsEditModalVisible] = useState(false);
  const [contentIndex, setContentIndex] = useState(0);
  const [filteredNmRegions, setFilteredNmRegions] = useState<NmRegion[] | null>(null);
  const [tccRegions, setTccRegions] = useState<TCCRegion[] | null>(null);
  const [filteredTccRegions, setFilteredTccRegions] = useState<TCCRegion[] | null>(null);
  const { mutate: updateTCC } = usePostSetTCCRegionMutation();
  const [modalState, setModalState] = useState({
    selectedFirstYear: 2021,
    selectedLastYear: 2021,
    selectedQuality: qualityOptions[2],
    selectedNoOfVisits: 1,
    years: [],
    id: null
  });
  const navigation = useNavigation();
  const { handleUpdateNMList: handleUpdateNM, nmRegions, setNmRegions, setUserData } = useRegion();
  const [search, setSearch] = useState<string>('');

  useEffect(() => {
    const currentYear = moment().year();
    let yearSelector: { label: string; value: number }[] = [{ label: 'visited', value: 1 }];
    for (let i = currentYear; i >= 1951; i--) {
      yearSelector.push({ label: i.toString(), value: i });
    }
    handleModalStateChange({ years: yearSelector });
  }, []);

  const handleModalStateChange = (updates: { [key: string]: any }) => {
    setModalState((prevState) => ({ ...prevState, ...updates }));
  };

  const handleOpenEditModal = (item: NmRegion) => {
    // handleModalStateChange({
    //   selectedFirstYear: item.year,
    //   selectedLastYear: item.last,
    //   selectedQuality:
    //     qualityOptions.find((quality) => quality.id === item.quality) || qualityOptions[2],
    //   selectedNoOfVisits: item.visits || 1,
    //   id: item.id
    // });
    // // setIsEditModalVisible(true);
    // navigation.navigate(
    //   ...([NAVIGATION_PAGES.EDIT_NM_DATA, { regionId: item.id, regionsList: true }] as never)
    // );
    navigation.navigate(
      ...([
        NAVIGATION_PAGES.TRIPS_2025,
        { region: { id: item.id, name: item.region_name } }
      ] as never)
    );
  };

  const handleUpdateTCC = useCallback(
    (region: number, visits: 0 | 1) => {
      const updatedTCC = tccRegions?.map((item) => {
        if (item.id === region) {
          return {
            ...item,
            visited: visits
          };
        }

        return item;
      });

      const updatedTCCData = {
        token,
        region,
        visits
      };

      updateTCC(updatedTCCData);
      updatedTCC && setTccRegions(updatedTCC);
    },
    [tccRegions]
  );

  const handleMegaSelect = (mega: { name: string; id: number }) => {
    setSelectedMega(mega);
    setSelectedCountry(null);
    setMegaSelectorVisible(false);
  };

  const handleCountrySelect = (country: { name: string; id: number }) => {
    setSelectedCountry(country);
    setSelectedMega({ id: 'all', name: 'ALL MEGAREGIONS' });
    setCountrySelectorVisible(false);
  };

  useEffect(() => {
    if (nmRegions && nmRegions.length && token) {
      calcTotalCountries();
    }
  }, [nmRegions]);

  useEffect(() => {
    if (regionsQe && regionsQe.result === 'OK') {
      setNmRegions(
        regionsQe.data.regions.map((region) => ({
          id: region.id,
          flag_1: region.flag1,
          flag_2: region.flag2,
          region_name: region.name,
          essential: 0,
          quality: region.best_visit_quality || null,
          year: region.first_visited_in_year || null,
          last: region.last_visited_in_year || null,
          visits: region.no_of_visits || 0,
          future: region.future,
          edit_in_trips: region.edit_in_trips
        }))
      );
      setTccRegions(regionsQe.data.tcc);
    }
  }, [regionsQe]);

  useEffect(() => {
    if (megaregions && megaregions.result === 'OK') {
      setContentIndex(0);
    }
  }, [selectedMega, selectedCountry]);

  const applyFilters = () => {
    let newNmData = nmRegions ?? [];
    let newTccData = tccRegions ?? [];

    switch (contentIndex) {
      case 1:
        newNmData = nmRegions?.filter((item: NmRegion) => item.visits <= 0) || [];
        newTccData = tccRegions?.filter((item) => item.visited <= 0) || [];
        break;
      case 2:
        newNmData = nmRegions?.filter((item: NmRegion) => item.visits > 0) || [];
        newTccData = tccRegions?.filter((item) => item.visited > 0) || [];
        break;
    }

    if (search) {
      newNmData = newNmData?.filter((item: NmRegion) => {
        const itemData = item.region_name ? item.region_name.toLowerCase() : '';
        return itemData.includes(search.toLowerCase());
      });
      newTccData = newTccData?.filter((item: TCCRegion) => {
        const itemData = item.name ? item.name.toLowerCase() : '';
        return itemData.includes(search.toLowerCase());
      });
    }

    setFilteredNmRegions(newNmData);
    setFilteredTccRegions(newTccData);
  };

  useEffect(() => {
    applyFilters();
  }, [contentIndex, nmRegions, tccRegions, search]);

  useEffect(() => {
    setSearch('');
  }, [contentIndex, selectedMega, selectedCountry]);

  useEffect(() => {
    if (megaregions && megaregions.result === 'OK') {
      setSelectedMega({ id: 'all', name: 'ALL MEGAREGIONS' });
    }
  }, [megaregions]);

  const calcTotalCountries = () => {
    const visited = nmRegions?.filter((item: NmRegion) => item.visits > 0).length || 0;
    setTotal(visited);
  };

  const searchFilter = (text: string) => {
    setSearch(text);
  };

  const renderItem = ({ item }: { item: NmRegion }) => (
    <TouchableOpacity
      onPress={() => {
        setUserData({
          type: 'nm',
          id: item.id,
          region_flag: item.flag_1,
          region_name: item.region_name,
          best_visit_quality: item.quality,
          first_visit_year: item.year,
          last_visit_year: item.last,
          no_of_visits: item.visits,
          visited: item.visits > 0,
          future: item.future,
          edit_in_trips: item.edit_in_trips
        });
        navigation.navigate(
          ...([
            NAVIGATION_PAGES.REGION_PREVIEW,
            {
              regionId: item.id,
              isTravelsScreen: true,
              type: 'nm',
              disabled: token ? false : true
            }
          ] as never)
        );
      }}
    >
      <NmRegionItem
        item={item}
        openEditModal={handleOpenEditModal}
        updateNM={handleUpdateNM}
        token={token}
      />
    </TouchableOpacity>
  );

  return (
    <PageWrapper>
      <Header label="Regions" />
      <TouchableOpacity style={styles.megaSelector} onPress={() => setMegaSelectorVisible(true)}>
        <Text style={styles.megaButtonText}>{selectedMega?.name}</Text>
        <ChevronIcon width={18} height={18} />
      </TouchableOpacity>

      <TouchableOpacity style={styles.megaSelector} onPress={() => setCountrySelectorVisible(true)}>
        <Text style={styles.megaButtonText}>{selectedCountry?.name || 'ALL COUNTRIES'}</Text>
        <ChevronIcon width={18} height={18} />
      </TouchableOpacity>

      <View style={{ marginBottom: 16 }}>
        <Input
          inputMode={'search'}
          placeholder={'Search'}
          onChange={(text) => searchFilter(text)}
          value={search}
          icon={<SearchIcon fill={'#C8C8C8'} width={14} height={14} />}
          height={34}
        />
      </View>

      {token && (
        <View style={styles.buttonContainer}>
          <CustomButton
            title="All"
            onPress={() => setContentIndex(0)}
            isActive={contentIndex === 0}
          />
          <CustomButton
            title="Visited"
            onPress={() => setContentIndex(2)}
            isActive={contentIndex === 2}
          />
          <CustomButton
            title="Not visited"
            onPress={() => setContentIndex(1)}
            isActive={contentIndex === 1}
          />
        </View>
      )}

      <View style={styles.progressHeader}>
        <Text style={styles.textSmall}>Visited regions</Text>
        <Text style={styles.textSmall}>
          {nmRegions?.length
            ? `${total}/${nmRegions.length} • ${((total * 100) / nmRegions.length).toFixed(2)}%`
            : '0/0 • 100%'}
        </Text>
      </View>

      <Progress.Bar
        progress={nmRegions?.length ? total / nmRegions.length : 1}
        width={null}
        height={4}
        color={Colors.DARK_BLUE}
        borderWidth={0}
        borderRadius={5}
        unfilledColor={Colors.FILL_LIGHT}
      />

      {filteredNmRegions && (filteredNmRegions?.length || filteredTccRegions?.length) ? (
        <FlatList
          data={filteredNmRegions}
          renderItem={renderItem}
          keyExtractor={(item) => item.id.toString()}
          showsVerticalScrollIndicator={false}
          style={{ paddingVertical: 8 }}
          ListFooterComponent={
            filteredTccRegions && filteredTccRegions.length ? (
              <View style={{ marginVertical: 8 }}>
                <Text style={[styles.textMedium, { textAlign: 'center' }]}>TCC regions</Text>
                {filteredTccRegions?.map((item) => (
                  <RegionItem
                    item={item}
                    updateRegion={handleUpdateTCC}
                    key={item.id}
                    token={token}
                    isTCCRegion={true}
                  />
                ))}
              </View>
            ) : null
          }
        />
      ) : null}

      <MegaregionsModal
        isVisible={megaSelectorVisible}
        onClose={() => setMegaSelectorVisible(false)}
        onSelect={handleMegaSelect}
        data={
          megaregions?.data
            ? [{ id: 'all' as never, name: 'ALL MEGAREGIONS' }, ...megaregions?.data]
            : []
        }
      />

      <MegaregionsModal
        isVisible={countrySelectorVisible}
        onClose={() => setCountrySelectorVisible(false)}
        onSelect={handleCountrySelect}
        data={
          countriesList?.data
            ? [
                { id: 'all' as never, name: 'ALL COUNTRIES', flag: null as never },
                ...countriesList?.data
              ]
            : []
        }
        isCountry={true}
      />

      <EditNmModal
        isVisible={isEditModalVisible}
        onClose={() => setIsEditModalVisible(false)}
        modalState={modalState}
        updateModalState={handleModalStateChange}
        updateNM={handleUpdateNM}
      />
    </PageWrapper>
  );
};

export default RegionsScreen;
