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

import { Button, CheckBox, EditNmModal, Header, PageWrapper } from 'src/components';
import { NmRegionItem } from '../Components/MyRegionsItems/NmRegionItem';

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

import { NAVIGATION_PAGES } from 'src/types';
import { useRegion } from 'src/contexts/RegionContext';
import { API_HOST } from 'src/constants';
import { getFontSize } from 'src/utils';
import { fetchCountryUserData } from '@api/countries';

const EditCountryDataScreen = ({ route }: { route: any }) => {
  const countryId = route?.params?.countryId;
  const countryName = route?.params?.countryName;
  const countryFlag = route?.params?.countryFlag;
  const slow11 = route?.params?.slow11;
  const slow31 = route?.params?.slow31;
  const slow101 = route?.params?.slow101;
  const isSlowList = route?.params?.isSlowList;

  const token = storage.get('token', StoreType.STRING) as string;
  const { data: regionsQe, refetch } = useGetRegionsQuery(
    undefined,
    countryId,
    String(token),
    true
  );
  const [isEnabled11, setIsEnabled11] = useState(Boolean(slow11));
  const [isEnabled31, setIsEnabled31] = useState(Boolean(slow31));
  const [isEnabled101, setIsEnabled101] = useState(Boolean(slow101));
  const [total, setTotal] = useState(0);
  const [isEditModalVisible, setIsEditModalVisible] = useState(false);
  const [filteredNmRegions, setFilteredNmRegions] = useState<NmRegion[] | null>(null);
  const [modalState, setModalState] = useState({
    selectedFirstYear: 2021,
    selectedLastYear: 2021,
    selectedQuality: qualityOptions[2],
    selectedNoOfVisits: 1,
    years: [],
    id: null
  });
  const [dataLoaded, setDataLoaded] = useState(false);
  const navigation = useNavigation();
  const {
    handleUpdateNMList: handleUpdateNM,
    handleUpdateSlowList: handleUpdateSlowList,
    handleUpdateSlow: handleUpdateSlow,
    nmRegions,
    setNmRegions,
    setUserData
  } = useRegion();
  const { mutateAsync: mutateCountriesData } = fetchCountryUserData();

  useEffect(() => {
    navigation.getParent()?.setOptions({
      tabBarStyle: {
        display: 'none'
      }
    });
  }, [navigation]);

  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 });
  }, []);

  useFocusEffect(
    useCallback(() => {
      const refetchData = async () => {
        refetch();
        await mutateCountriesData(
          { id: countryId, token },
          {
            onSuccess: (data) => {
              setUserData({ type: 'countries', id: countryId, ...data.data });
            }
          }
        );
      };

      refetchData();
    }, [token, countryId, navigation])
  );

  const updateRegion = async (nm: any) => {
    handleUpdateNM(nm.id, nm.visits > 0 ? 0 : 1, nm.visits > 0 ? 0 : 1, nm.visits > 0 ? 0 : 1, 3);
    setTimeout(async () => {
      await mutateCountriesData(
        { id: countryId, token },
        {
          onSuccess: (data) => {
            setUserData({ type: 'countries', id: countryId, ...data.data });
          }
        }
      );
    }, 1000);
  };

  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 }] as never));
    navigation.navigate(
      ...([
        NAVIGATION_PAGES.TRIPS_2025,
        { region: { id: item.id, name: item.region_name } }
      ] as never)
    );
  };

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

  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
        }))
      );
      setDataLoaded(true);
    }
  }, [regionsQe]);

  useEffect(() => {
    setFilteredNmRegions(nmRegions ?? []);
  }, [nmRegions]);

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

    if (visited === 0 && dataLoaded) {
      setIsEnabled11(false);
      setIsEnabled31(false);
      setIsEnabled101(false);
    }
    setTotal(visited);
  };

  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={() => updateRegion(item)}
        token={token}
        hideCountry={true}
      />
    </TouchableOpacity>
  );

  return (
    <PageWrapper>
      <Header
        label={
          <View style={{ flexDirection: 'row', alignItems: 'center' }}>
            <Text
              style={{
                fontFamily: 'redhat-700',
                fontSize: getFontSize(14),
                color: Colors.DARK_BLUE
              }}
            >
              {countryName}
            </Text>
            <Image
              source={{ uri: API_HOST + countryFlag }}
              style={{
                width: 24,
                height: 24,
                marginLeft: 8,
                borderRadius: 12,
                borderWidth: 0.5,
                borderColor: Colors.BORDER_LIGHT
              }}
            />
          </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 ? (
        <FlatList
          data={filteredNmRegions}
          renderItem={renderItem}
          keyExtractor={(item) => item.id.toString()}
          showsVerticalScrollIndicator={false}
          style={{ paddingVertical: 8 }}
        />
      ) : null}

      <View style={styles.optionsContainer}>
        <TouchableOpacity
          disabled={isEnabled31 || isEnabled101 || total === 0}
          onPress={() => {
            setIsEnabled11(!isEnabled11);
            setIsEnabled31(isEnabled11 ? false : isEnabled31);
          }}
          style={styles.optionBtn}
          hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }}
        >
          <CheckBox
            onChange={() => {
              setIsEnabled11(!isEnabled11);
              setIsEnabled31(isEnabled11 ? false : isEnabled31);
            }}
            value={isEnabled11}
            color={Colors.DARK_BLUE}
            disabled={isEnabled31 || isEnabled101 || total === 0}
          />
          <Text style={styles.optionText}>11+ days</Text>
        </TouchableOpacity>
        <TouchableOpacity
          disabled={!isEnabled11 || isEnabled101}
          onPress={() => {
            setIsEnabled31(!isEnabled31);
            setIsEnabled101(isEnabled31 ? false : isEnabled101);
          }}
          style={styles.optionBtn}
          hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }}
        >
          <CheckBox
            onChange={() => {
              setIsEnabled31(!isEnabled31);
              setIsEnabled101(isEnabled31 ? false : isEnabled101);
            }}
            value={isEnabled31}
            color={Colors.DARK_BLUE}
            disabled={!isEnabled11 || isEnabled101}
          />
          <Text style={styles.optionText}>31+ days</Text>
        </TouchableOpacity>
        <TouchableOpacity
          disabled={!isEnabled11 || !isEnabled31}
          onPress={() => setIsEnabled101(!isEnabled101)}
          style={styles.optionBtn}
          hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }}
        >
          <CheckBox
            onChange={() => setIsEnabled101(!isEnabled101)}
            value={isEnabled101}
            color={Colors.DARK_BLUE}
            disabled={!isEnabled11 || !isEnabled31}
          />
          <Text style={styles.optionText}>101+ days</Text>
        </TouchableOpacity>
      </View>
      <View style={{ marginBottom: 24 }}>
        <Button
          children="Done"
          onPress={() => {
            if (total === 0) {
              navigation.goBack();
              isSlowList
                ? handleUpdateSlowList(countryId, false, undefined, undefined, undefined)
                : handleUpdateSlow(countryId, false, undefined, undefined, undefined);
              return;
            }
            isSlowList
              ? handleUpdateSlowList(countryId, undefined, isEnabled11, isEnabled31, isEnabled101)
              : handleUpdateSlow(countryId, undefined, isEnabled11, isEnabled31, isEnabled101);
            navigation.goBack();
          }}
        />
      </View>

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

export default EditCountryDataScreen;
