import React, { useCallback, useEffect, useRef, useState } from 'react';
import {
  View,
  Text,
  Image,
  TouchableOpacity,
  ScrollView,
  Dimensions,
  Switch,
  Pressable,
  Animated
} from 'react-native';
import { Colors } from 'src/theme';
import { styles } from './styles';
import { Loading } from 'src/components';

import CheckSvg from 'assets/icons/mark.svg';
import CloseSVG from 'assets/icons/close.svg';
import ArrowIcon from 'assets/icons/mark-to-up.svg';
import { API_HOST } from 'src/constants';
import { FlashList, FlashListRef } from '@shopify/flash-list';
import { useNavigation } from '@react-navigation/native';
import { NAVIGATION_PAGES } from 'src/types';

interface Mega {
  id: number;
  name: string;
  regions: {
    id: number;
    name: string;
    flag1: string;
    flag2: string | null;
  }[];
  transits: number[];
  visits: number[];
  total?: number;
}

interface Region {
  id: number;
  name: string;
  flag1: string;
  flag2: string | null;
  country_id: number;
}

const RegionsRenderer = ({
  type,
  regions,
  setIsModalVisible
}: {
  type: string;
  regions: any;
  setIsModalVisible: (value: boolean) => void;
}) => {
  const navigation = useNavigation();
  const flashlistConfig = {
    waitForInteraction: true,
    itemVisiblePercentThreshold: 50,
    minimumViewTime: 1000
  };
  const isSmallWidth = Dimensions.get('window').width < 383;
  const [showAll, setShowAll] = useState<'all' | 'visited' | 'not_visited'>('all');
  const [filteredRegions, setFilteredRegions] = useState<any[]>([]);
  const [filteredMegaregions, setFilteredMegaregions] = useState<any[]>([]);
  const disabled = type === 'whs' || type === 'tcc' ? true : false;

  const [dropdownOpen, setDropdownOpen] = useState(false);

  const animation = useRef(new Animated.Value(0)).current;

  useEffect(() => {
    Animated.timing(animation, {
      toValue: dropdownOpen ? 1 : 0,
      duration: 100,
      useNativeDriver: true
    }).start();
  }, [dropdownOpen]);

  const showAllLabels: Record<'all' | 'visited' | 'not_visited', string> = {
    all: 'All',
    visited: 'Visited',
    not_visited: 'Not Visited'
  };

  const flashListRef = useRef<FlashListRef<any> | null>(null);

  useEffect(() => {
    if (!regions?.data) return;

    if (showAll === 'all') {
      switch (type) {
        case 'nm':
        case 'mqp':
          setFilteredMegaregions(regions.data.megaregions);
          break;
        case 'un':
        case 'unp':
        case 'slow':
        case 'yes':
        case 'tcc':
          setFilteredRegions(regions.data[0]);
          break;
        case 'whs':
          setFilteredRegions(regions.data);
          break;
      }
    } else if (showAll === 'visited') {
      switch (type) {
        case 'nm':
        case 'mqp':
          const filteredMegaregions = regions.data?.megaregions
            ?.map((item: Mega) => ({
              ...item,
              regions: item.regions.filter((region) => item.visits.includes(region.id)),
              total: item.regions.length
            }))
            ?.filter((item: Mega) => item.regions.length > 0);

          setFilteredMegaregions(filteredMegaregions);
          break;
        case 'un':
        case 'unp':
        case 'tcc':
          setFilteredRegions(
            regions.data[0].filter((item: Region) => regions.data[1].includes(item.name))
          );
          break;
        case 'slow':
          setFilteredRegions(regions.data[0].filter((item: any) => item.visited === 1));
          break;
        case 'whs':
          setFilteredRegions(regions.data.filter((item: any) => item.visited));
          break;
      }
    } else {
      switch (type) {
        case 'nm':
        case 'mqp':
          const filteredMegaregions = regions.data?.megaregions
            ?.map((item: Mega) => ({
              ...item,
              regions: item.regions.filter((region) => !item.visits.includes(region.id)),
              total: item.regions.length
            }))
            ?.filter((item: Mega) => item.regions.length > 0);

          setFilteredMegaregions(filteredMegaregions);
          break;
        case 'un':
        case 'unp':
        case 'tcc':
          setFilteredRegions(
            regions.data[0].filter((item: Region) => !regions.data[1].includes(item.name))
          );
          break;
        case 'slow':
          setFilteredRegions(regions.data[0].filter((item: any) => item.visited === 0));
          break;
        case 'whs':
          setFilteredRegions(regions.data.filter((item: any) => !item.visited));
          break;
      }
    }

    if (flashListRef && flashListRef.current) {
      flashListRef.current?.scrollToOffset({ offset: 0, animated: false });
    }
  }, [showAll, regions]);

  const getOpacity = useCallback(
    (item: any, mega?: Mega) => {
      switch (type) {
        case 'nm':
        case 'mqp':
          return mega?.visits.includes(item.id) ? 1 : 0.4;
        case 'un':
        case 'unp':
        case 'tcc':
          return regions.data[1].includes(item.name) ? 1 : 0.4;
        case 'slow':
          return item.visited === 1 ? 1 : 0.4;
        case 'whs':
          return item.visited ? 1 : 0.4;
        default:
          return 1;
      }
    },
    [type, regions?.data]
  );

  const handlePress = (item: any) => {
    switch (type) {
      case 'nm':
      case 'mqp':
        setIsModalVisible(false);
        navigation.navigate(
          ...([
            NAVIGATION_PAGES.REGION_PREVIEW,
            {
              regionId: item.id,
              type: type === 'nm' ? 'nm' : 'dare',
              disabled: false,
              isProfileScreen: true
            }
          ] as never)
        );
        break;
      case 'slow':
      case 'yes':
      case 'un':
      case 'unp':
        setIsModalVisible(false);
        navigation.navigate(
          ...([
            NAVIGATION_PAGES.COUNTRY_PREVIEW,
            {
              regionId: type === 'slow' ? item.country_id : item.id,
              type: 'country',
              disabled: false,
              isProfileScreen: true
            }
          ] as never)
        );
        break;
    }
  };

  const renderRegion = useCallback(
    (item: any, mega?: Mega) => {
      return (
        <TouchableOpacity
          style={[styles.regionRow, { opacity: getOpacity(item, mega) }]}
          onPress={() => handlePress(item)}
          disabled={disabled}
        >
          <View
            style={[
              styles.flags,
              type === 'yes' ? { flex: 2 } : type === 'slow' ? { flex: 1 } : {}
            ]}
          >
            <Image
              source={{
                uri:
                  API_HOST +
                  (type === 'whs'
                    ? item.flag
                    : type === 'slow'
                      ? '/img/flags_new/' + item?.flag
                      : '/img/flags_new/' + item?.flag1)
              }}
              style={styles.regionsFlag}
            />
            {item?.flag2 ? (
              <Image
                source={{ uri: API_HOST + '/img/flags_new/' + item.flag2 }}
                style={[styles.regionsFlag, { marginLeft: -18 }]}
              />
            ) : null}
            <View style={styles.regionInfo}>
              <Text style={styles.regionName}>{type === 'slow' ? item.country : item?.name}</Text>
            </View>
          </View>
          {type === 'nm' && (
            <View style={{ flexDirection: 'row', flex: isSmallWidth ? 2.5 : 2 }}>
              <View style={{ width: '56%', alignItems: 'center', marginRight: '2%' }}>
                {regions.data.firsts[item?.id] && regions.data.firsts[item?.id] !== 1 ? (
                  <Text
                    style={[
                      styles.regionName,
                      { fontSize: isSmallWidth ? 11 : 12, fontWeight: '700' }
                    ]}
                  >
                    {regions.data.firsts[item?.id]}
                  </Text>
                ) : null}
              </View>
              <View style={{ width: '42%', alignItems: 'center' }}>
                {regions.data.last[item?.id] && regions.data.last[item?.id] !== 1 ? (
                  <Text
                    style={[
                      styles.regionName,
                      { fontSize: isSmallWidth ? 11 : 12, fontWeight: '700' }
                    ]}
                  >
                    {regions.data.last[item?.id]}
                  </Text>
                ) : null}
              </View>
            </View>
          )}
          {type === 'yes' && (
            <View style={{ flexDirection: 'row', flex: 1 }}>
              <View style={{ width: '60%', alignItems: 'center' }}>
                {regions.data[1][item?.id] && regions.data[1][item?.id].year !== 1 ? (
                  <Text style={[styles.regionName, { fontSize: 12, fontWeight: '700' }]}>
                    {regions.data[1][item?.id].year}
                  </Text>
                ) : null}
              </View>
              <View style={{ width: '40%', alignItems: 'center' }}>
                {regions.data[1][item?.id] ? (
                  <Text style={[styles.regionName, { fontSize: 12, fontWeight: '700' }]}>
                    {regions.data[1][item?.id].score}
                  </Text>
                ) : null}
              </View>
            </View>
          )}
          {type === 'slow' && (
            <View style={{ flexDirection: 'row', flex: 1 }}>
              <View style={{ width: '33%', alignItems: 'center' }}>
                {item.slow11 === 1 ? (
                  <CheckSvg fill={Colors.DARK_BLUE} width={14} height={14} />
                ) : null}
              </View>
              <View style={{ width: '33%', alignItems: 'center' }}>
                {item.slow31 === 1 ? (
                  <CheckSvg fill={Colors.DARK_BLUE} width={14} height={14} />
                ) : null}
              </View>
              <View style={{ width: '33%', alignItems: 'center' }}>
                {item.slow101 === 1 ? (
                  <CheckSvg fill={Colors.DARK_BLUE} width={14} height={14} />
                ) : null}
              </View>
            </View>
          )}
        </TouchableOpacity>
      );
    },
    [getOpacity, regions?.data, type]
  );

  const renderMegaregion = useCallback(
    ({ item }: { item: Mega }) => {
      return (
        <View style={styles.megaregion}>
          <View style={styles.blockTitle}>
            <Text style={[styles.megaregionTitle, type === 'mqp' ? { textAlign: 'center' } : {}]}>
              {type === 'nm' ? '- ' : ''}
              {item.name}
              <Text style={{ fontWeight: '600' }}>
                {' '}
                - {item.visits.length}/{item?.total ?? item.regions.length} (
                {((item.visits.length * 100) / (item?.total ?? item.regions.length)).toFixed(2)}%)
              </Text>
            </Text>
            {type === 'nm' && (
              <View style={{ flexDirection: 'row', flex: isSmallWidth ? 2.5 : 2 }}>
                <View style={{ width: '56%', alignItems: 'center', marginRight: '2%' }}>
                  <Text style={styles.alignCenter}>
                    <Text style={[styles.megaregionTitle, { fontSize: isSmallWidth ? 11 : 12 }]}>
                      First
                    </Text>
                    {'\n'}
                    <Text style={[styles.megaregionTitle, { fontSize: isSmallWidth ? 11 : 12 }]}>
                      visited
                    </Text>
                  </Text>
                </View>
                <View style={{ width: '42%', alignItems: 'center' }}>
                  <Text style={styles.alignCenter}>
                    <Text style={[styles.megaregionTitle, { fontSize: isSmallWidth ? 11 : 12 }]}>
                      Last
                    </Text>
                    {'\n'}
                    <Text style={[styles.megaregionTitle, { fontSize: isSmallWidth ? 11 : 12 }]}>
                      visit
                    </Text>
                  </Text>
                </View>
              </View>
            )}
          </View>

          <View style={styles.megaSubList}>
            <ScrollView
              style={{ flex: 1 }}
              nestedScrollEnabled={true}
              showsVerticalScrollIndicator={false}
              horizontal={false}
            >
              {item.regions?.map((region: any) => (
                <View key={region.id}>{renderRegion(region, item)}</View>
              ))}
            </ScrollView>
          </View>
        </View>
      );
    },
    [flashlistConfig, renderRegion, type]
  );

  const renderContent = () => {
    const renderHeader = (headerText: string, rightElement: boolean) => (
      <RegionsModalHeader
        textHeader={headerText}
        onRequestClose={() => setIsModalVisible(false)}
        rightElement={
          rightElement ? (
            <View style={{ alignItems: 'flex-end' }}>
              <Pressable
                onPress={() => setDropdownOpen((prev) => !prev)}
                style={{
                  paddingHorizontal: 10,
                  paddingVertical: 6,
                  borderRadius: 6,
                  borderWidth: 1,
                  borderColor: Colors.BORDER_LIGHT,
                  flexDirection: 'row',
                  alignItems: 'center',
                  justifyContent: 'space-between',
                  minWidth: 110
                }}
              >
                <Text
                  style={{
                    fontSize: 12,
                    fontWeight: '600',
                    color: Colors.DARK_BLUE,
                    marginRight: 6
                  }}
                >
                  {showAllLabels[showAll]}
                </Text>

                <Animated.View
                  style={{
                    transform: [
                      {
                        rotate: animation.interpolate({
                          inputRange: [0, 1],
                          outputRange: ['0deg', '180deg']
                        })
                      }
                    ]
                  }}
                >
                  <ArrowIcon height={12} width={12} stroke={Colors.BORDER_LIGHT} />
                </Animated.View>
              </Pressable>

              {dropdownOpen && (
                <Pressable
                  onPress={() => setDropdownOpen(false)}
                  style={{
                    position: 'absolute',
                    top: -1000,
                    left: -1000,
                    right: -1000,
                    bottom: -1000,
                    zIndex: 1
                  }}
                />
              )}

              {dropdownOpen && (
                <Animated.View
                  pointerEvents="auto"
                  style={{
                    position: 'absolute',
                    top: 36,
                    right: 0,
                    backgroundColor: Colors.WHITE,
                    borderRadius: 8,
                    paddingVertical: 6,
                    minWidth: 150,
                    borderWidth: 1,
                    borderColor: Colors.BORDER_LIGHT,
                    opacity: animation,
                    zIndex: 1000,
                    elevation: 10,
                    transform: [
                      {
                        translateY: animation.interpolate({
                          inputRange: [0, 1],
                          outputRange: [-6, 0]
                        })
                      }
                    ]
                  }}
                >
                  {(Object.keys(showAllLabels) as Array<'all' | 'visited' | 'not_visited'>).map(
                    (key) => (
                      <Pressable
                        key={key}
                        onPress={() => {
                          setShowAll(key);
                          setDropdownOpen(false);
                        }}
                        style={{
                          paddingVertical: 10,
                          paddingHorizontal: 14,
                          flexDirection: 'row',
                          alignItems: 'center',
                          justifyContent: 'space-between'
                        }}
                      >
                        <Text
                          style={{
                            fontSize: 13,
                            color: Colors.DARK_BLUE,
                            fontWeight: '600'
                          }}
                        >
                          {showAllLabels[key]}
                        </Text>

                        {showAll === key && (
                          <CheckSvg fill={Colors.DARK_BLUE} height={12} width={12} />
                        )}
                      </Pressable>
                    )
                  )}
                </Animated.View>
              )}
            </View>
          ) : null
        }
      />
    );

    switch (type) {
      case 'nm':
      case 'mqp':
        return (
          <>
            {renderHeader(type === 'nm' ? 'NM' : 'DARE', true)}
            <FlashList
              ref={flashListRef}
              viewabilityConfig={flashlistConfig}
              data={filteredMegaregions}
              renderItem={renderMegaregion}
              keyExtractor={(megaregion) => megaregion?.id?.toString()}
              showsVerticalScrollIndicator={false}
              nestedScrollEnabled={true}
              contentContainerStyle={{ paddingTop: 8 }}
            />
          </>
        );
      case 'un':
      case 'unp':
      case 'tcc':
        return (
          <>
            {renderHeader(type === 'un' ? 'UN' : type === 'unp' ? 'UN+' : 'TCC', true)}
            <FlashList
              ref={flashListRef}
              viewabilityConfig={flashlistConfig}
              data={filteredRegions}
              renderItem={(region) => renderRegion(region.item)}
              keyExtractor={(region: Region) => region.name}
              showsVerticalScrollIndicator={false}
              contentContainerStyle={{ paddingTop: 8 }}
              ListHeaderComponent={() => (
                <View style={styles.blockTitle}>
                  <Text style={[styles.megaregionTitle, { textAlign: 'center' }]}>
                    {type === 'un' ? 'Countries' : 'Territories'}
                    <Text style={{ fontWeight: '600' }}>
                      {' '}
                      - {regions.data[3]}/{regions.data[2]} (
                      {((regions.data[3] * 100) / regions.data[2]).toFixed(2)}%)
                    </Text>
                  </Text>
                </View>
              )}
            />
          </>
        );
      case 'slow':
        return (
          <>
            {renderHeader('SLOW', true)}
            <FlashList
              ref={flashListRef}
              viewabilityConfig={flashlistConfig}
              data={filteredRegions}
              renderItem={(region) => renderRegion(region.item)}
              keyExtractor={(region: Region) => region.country_id?.toString()}
              showsVerticalScrollIndicator={false}
              contentContainerStyle={{ paddingTop: 8 }}
              ListHeaderComponent={() => {
                return (
                  <View style={styles.blockTitle}>
                    <Text style={[styles.megaregionTitle, { flex: 1 }]}>Countries</Text>
                    <View style={{ flexDirection: 'row', flex: 1 }}>
                      <View style={styles.slow}>
                        <Text style={styles.alignCenter}>
                          <Text style={[styles.megaregionTitle, { fontSize: 12 }]}>11+</Text>
                        </Text>
                      </View>
                      <View style={styles.slow}>
                        <Text style={styles.alignCenter}>
                          <Text style={[styles.megaregionTitle, { fontSize: 12 }]}>31+</Text>
                        </Text>
                      </View>
                      <View style={styles.slow}>
                        <Text style={styles.alignCenter}>
                          <Text style={[styles.megaregionTitle, { fontSize: 12 }]}>101+</Text>
                        </Text>
                      </View>
                    </View>
                  </View>
                );
              }}
            />
          </>
        );
      case 'yes':
        const calcTotalScore = (
          values: {
            year: number;
            score: number;
            country: string;
          }[]
        ) => {
          const totalScore = values.reduce((accumulator, item) => {
            return accumulator + item.score;
          }, 0);
          return totalScore;
        };
        return (
          <>
            {renderHeader('YES', false)}
            <FlashList
              ref={flashListRef}
              viewabilityConfig={flashlistConfig}
              data={regions.data[0]}
              renderItem={(region) => renderRegion(region.item)}
              keyExtractor={(region: Region) => region.id?.toString()}
              showsVerticalScrollIndicator={false}
              contentContainerStyle={{ paddingTop: 8 }}
              ListHeaderComponent={() => {
                return (
                  <View style={styles.blockTitle}>
                    <Text style={[styles.megaregionTitle, { flex: 2 }]}>
                      Countries
                      <Text style={{ fontWeight: '600' }}>
                        {' total score '}
                        {calcTotalScore(Object.values(regions.data[1]))}
                      </Text>
                    </Text>
                    <View style={{ flexDirection: 'row', flex: 1 }}>
                      <View style={{ width: '60%', alignItems: 'center' }}>
                        <Text style={styles.alignCenter}>
                          <Text style={[styles.megaregionTitle, { fontSize: 12 }]}>Last visit</Text>
                        </Text>
                      </View>
                      <View
                        style={{ width: '40%', alignItems: 'center', justifyContent: 'center' }}
                      >
                        <Text style={styles.alignCenter}>
                          <Text style={[styles.megaregionTitle, { fontSize: 12 }]}>Score</Text>
                        </Text>
                      </View>
                    </View>
                  </View>
                );
              }}
            />
          </>
        );
      case 'whs':
        return (
          <>
            {renderHeader('WHS', true)}
            <FlashList
              ref={flashListRef}
              viewabilityConfig={flashlistConfig}
              data={filteredRegions}
              renderItem={(region) => renderRegion(region.item)}
              keyExtractor={(region: Region) => region.name}
              showsVerticalScrollIndicator={false}
              contentContainerStyle={{ paddingTop: 8 }}
            />
          </>
        );
    }
  };

  return <View style={styles.modalContent}>{regions?.data ? renderContent() : <Loading />}</View>;
};

const RegionsModalHeader = ({
  textHeader,
  onRequestClose,
  rightElement
}: {
  textHeader: string;
  onRequestClose: () => void;
  rightElement?: any;
}) => {
  return (
    <View style={styles.header}>
      <TouchableOpacity onPress={onRequestClose} style={{ padding: 6 }}>
        <CloseSVG />
      </TouchableOpacity>
      <Text style={styles.headerText}>{textHeader}</Text>
      {rightElement ? rightElement : <View style={{ height: 30, width: 30 }} />}
    </View>
  );
};

export default RegionsRenderer;
