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

import { EditNmModal, Header, 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,
  useGetRegionQeQuery,
  usePostSetNmRegionMutation,
  usePostSetTCCRegionMutation
} from '@api/myRegions';
import { qualityOptions } from '../utils/constants';

import ChevronIcon from 'assets/icons/travels-screens/down-arrow.svg';

const RegionsScreen = () => {
  const token = storage.get('token', StoreType.STRING) as string;
  const { data: megaregions } = useGetMegaregionsQuery(token, true);
  const [megaSelectorVisible, setMegaSelectorVisible] = useState(false);
  const [selectedMega, setSelectedMega] = useState<{ name: string; id: number }>({
    id: 1,
    name: 'SOUTHERN EUROPE'
  });
  const { data: regionsQe } = useGetRegionQeQuery(selectedMega.id, String(token), true);
  const [total, setTotal] = useState(0);
  const [isEditModalVisible, setIsEditModalVisible] = useState(false);
  const [contentIndex, setContentIndex] = useState(0);
  const [nmRegions, setNmRegions] = useState<NmRegion[] | null>(null);
  const [filteredNmRegions, setFilteredNmRegions] = useState<NmRegion[] | null>(null);
  const [tccRegions, setTccRegions] = useState<TCCRegion[] | null>(null);
  const [filteredTccRegions, setFilteredTccRegions] = useState<TCCRegion[] | null>(null);
  const { mutate: updateNM } = usePostSetNmRegionMutation();
  const { mutate: updateTCC } = usePostSetTCCRegionMutation();
  const [modalState, setModalState] = useState({
    selectedFirstYear: 2021,
    selectedLastYear: 2021,
    selectedQuality: qualityOptions[2],
    selectedNoOfVisits: 1,
    years: [],
    id: null
  });

  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);
  };

  const handleUpdateNM = useCallback(
    (id: number, first: number, last: number, visits: number, quality: number) => {
      const updatedNM = nmRegions?.map((item) => {
        if (item.id === id) {
          return {
            ...item,
            year: first,
            last,
            quality,
            visits
          };
        }

        return item;
      });

      const updatedNMData = {
        token,
        region: id,
        first,
        last,
        visits,
        quality
      };

      updateNM(updatedNMData);
      updatedNM && setNmRegions(updatedNM);
    },
    [nmRegions]
  );

  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]
  );

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

  useEffect(() => {
    if (regionsQe && regionsQe.result === 'OK') {
      setNmRegions(regionsQe.data.out_regs);
      setTccRegions(regionsQe.data.out_tcc);
    }
  }, [regionsQe]);

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

  useEffect(() => {
    switch (contentIndex) {
      case 0:
        setFilteredNmRegions(nmRegions);
        setFilteredTccRegions(tccRegions);
        break;
      case 1:
        setFilteredNmRegions(nmRegions?.filter((item) => item.visits <= 0) || []);
        setFilteredTccRegions(tccRegions?.filter((item) => item.visited <= 0) || []);
        break;
      case 2:
        setFilteredNmRegions(nmRegions?.filter((item) => item.visits > 0) || []);
        setFilteredTccRegions(tccRegions?.filter((item) => item.visited > 0) || []);
        break;
    }
  }, [contentIndex, nmRegions, tccRegions]);

  useFocusEffect(
    useCallback(() => {
      if (megaregions && megaregions.result === 'OK') {
        setSelectedMega(megaregions.data[1]);
      }
    }, [megaregions])
  );

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

  const renderItem = ({ item }: { item: NmRegion }) => (
    <NmRegionItem item={item} openEditModal={handleOpenEditModal} updateNM={handleUpdateNM} token={token} />
  );

  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>

      {token && (
        <View style={styles.buttonContainer}>
          <CustomButton
            title="All"
            onPress={() => setContentIndex(0)}
            isActive={contentIndex === 0}
          />
          <CustomButton
            title="Not visited"
            onPress={() => setContentIndex(1)}
            isActive={contentIndex === 1}
          />
          <CustomButton
            title="Visited"
            onPress={() => setContentIndex(2)}
            isActive={contentIndex === 2}
          />
        </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} />
                ))}
              </View>
            ) : null
          }
        />
      ) : null}

      <MegaregionsModal
        isVisible={megaSelectorVisible}
        onClose={() => setMegaSelectorVisible(false)}
        onSelect={(object) => {
          setMegaSelectorVisible(false);
          setSelectedMega(object);
        }}
        data={megaregions?.data ?? []}
      />

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

export default RegionsScreen;
