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 { 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';
import { NAVIGATION_PAGES } from 'src/types';
import { useRegion } from 'src/contexts/RegionContext';

const DareScreen = () => {
  const token = (storage.get('token', StoreType.STRING) as string);
  const { data: megaregions } = useGetMegaregionsDareQuery(String(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, String(token), true);
  const [filteredDareRegions, setFilteredDareRegions] = useState<DareRegion[] | null>(null);
  const [total, setTotal] = useState(0);
  const [contentIndex, setContentIndex] = useState(0);
  const navigation = useNavigation();
  const {
    handleUpdateDareList: handleUpdateDare,
    dareRegions,
    setDareRegions,
    setUserData
  } = useRegion();

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

  useFocusEffect(
    useCallback(() => {
      navigation.getParent()?.setOptions({
        tabBarStyle: {
          display: 'flex',
          ...Platform.select({
            android: {
              height: 58
            }
          })
        }
      });
    }, [navigation])
  );

  useEffect(() => {
    if (dareRegions && dareRegions.length) {
      token && 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: DareRegion) => +item.visited <= 0) || []);
        break;
      case 2:
        setFilteredDareRegions(dareRegions?.filter((item: DareRegion) => +item.visited > 0) || []);
        break;
      case 3:
        setFilteredDareRegions(dareRegions?.filter((item: DareRegion) => item.new === 1) || []);
        break;
      default:
        setFilteredDareRegions(dareRegions);
    }
  }, [contentIndex, dareRegions]);

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

  const renderItem = ({ item }: { item: DareRegion }) => (
    <TouchableOpacity
      onPress={() => {
        setUserData({
          type: 'dare',
          region_flag: item.flag1,
          region_name: item.name,
          visited: +item.visited > 0
        });
        navigation.navigate(
          ...([
            NAVIGATION_PAGES.REGION_PREVIEW,
            {
              regionId: item.id,
              isTravelsScreen: true,
              type: 'dare',
              disabled: token ? false : true
            }
          ] as never)
        );
      }}
    >
      <RegionItem item={item} dare={true} updateRegion={handleUpdateDare} token={token} />
    </TouchableOpacity>
  );

  return (
    <PageWrapper>
      <Header
        label="DARE"
        // rightElement={
        //   <TouchableOpacity
        //     onPress={() => navigation.navigate(NAVIGATION_PAGES.DARE_INFO as never)}
        //     style={{ width: 30 }}
        //   >
        //     <InfoIcon />
        //   </TouchableOpacity>
        // }
      />
      <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}
          />
          <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.FILL_LIGHT}
      />

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

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

export default DareScreen;
