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 { Header, PageWrapper } from 'src/components';
import { CustomButton } from '../Components';
import MegaregionsModal from '../Components/MegaregionsModal';

import { StoreType, storage } from 'src/storage';
import { DareRegion } from '../utils/types';
import { Colors } from 'src/theme';
import { styles } from '../RegionsScreen/styles';
import { RegionItem } from '../Components/MyRegionsItems/RegionItem';
import {
  useGetMegaregionsDareQuery,
  useGetRegionDareQuery,
  usePostSetDareRegionMutation
} from '@api/myDARE';

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

const DareScreen = () => {
  const token = storage.get('token', StoreType.STRING) as string;
  const { data: megaregions } = useGetMegaregionsDareQuery(token, true);
  const [megaSelectorVisible, setMegaSelectorVisible] = useState(false);
  const [selectedMega, setSelectedMega] = useState<{ name: string; id: number }>({
    id: 1,
    name: 'SOUTHERN EUROPE'
  });
  const { data: dareData } = useGetRegionDareQuery(selectedMega.id, token, true);
  const [dareRegions, setDareRegions] = useState<DareRegion[] | null>(null);
  const [filteredDareRegions, setFilteredDareRegions] = useState<DareRegion[] | null>(null);
  const [total, setTotal] = useState(0);
  const [contentIndex, setContentIndex] = useState(0);
  const { mutate: updateDARE } = usePostSetDareRegionMutation();

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

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

  useEffect(() => {
    if (dareData && dareData.result === 'OK') {
      setDareRegions(dareData.data);
    }
  }, [dareData]);

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

  useEffect(() => {
    switch (contentIndex) {
      case 1:
        setFilteredDareRegions(dareRegions?.filter((item) => +item.visited <= 0) || []);
        break;
      case 2:
        setFilteredDareRegions(dareRegions?.filter((item) => +item.visited > 0) || []);
        break;
      case 3:
        setFilteredDareRegions(dareRegions?.filter((item) => item.new === 1) || []);
        break;
      default:
        setFilteredDareRegions(dareRegions);
    }
  }, [contentIndex, dareRegions]);

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

  const handleUpdateDare = useCallback(
    (region: number, visits: 0 | 1) => {
      const updatedDARE = dareRegions?.map((item) => {
        if (item.id === region) {
          return {
            ...item,
            visited: String(visits)
          };
        }

        return item;
      });

      const updatedDareData = {
        token,
        region,
        visits
      };

      updateDARE(updatedDareData);
      updatedDARE && setDareRegions(updatedDARE);
    },
    [dareRegions]
  );

  const renderItem = ({ item }: { item: DareRegion }) => (
    <RegionItem item={item} dare={true} updateRegion={handleUpdateDare} />
  );

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

      <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}
        />
        <CustomButton
          title="New"
          onPress={() => setContentIndex(3)}
          isActive={contentIndex === 3}
          flex={0.6}
        />
      </View>

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

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

      {filteredDareRegions && (filteredDareRegions?.length || filteredDareRegions?.length) ? (
        <FlatList
          data={filteredDareRegions}
          renderItem={renderItem}
          keyExtractor={(item) => item.id.toString()}
          showsVerticalScrollIndicator={false}
          style={{ paddingTop: 8, marginBottom: 16 }}
        />
      ) : null}

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

export default DareScreen;
