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, Input, 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';
import SearchIcon from 'assets/icons/search.svg';

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();
  const [search, setSearch] = useState<string>('');

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

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

  const applyFilters = () => {
    let newDareData = dareRegions ?? [];

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

    if (search) {
      newDareData = newDareData?.filter((item: DareRegion) => {
        const itemData = item.name ? item.name.toLowerCase() : '';
        return itemData.includes(search.toLowerCase());
      });
    }

    setFilteredDareRegions(newDareData);
  };

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

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

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

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

  const renderItem = ({ item }: { item: DareRegion }) => (
    <TouchableOpacity
      onPress={() => {
        setUserData({
          type: 'dare',
          id: item.id,
          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>

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