import React from 'react';
import { View, Text, Image, TouchableOpacity } from 'react-native';
import { styles } from './styles';
import { Loading } from 'src/components';

import CloseSVG from 'assets/icons/close.svg';
import { API_HOST } from 'src/constants';
import { FlashList } from '@shopify/flash-list';
import { useNavigation } from '@react-navigation/native';
import { Dare, NewNM, PostGetUpdateReturn, SeriesOrWhs, UnOrUnp } from '@api/user';
import { NAVIGATION_PAGES } from 'src/types';

interface UpdatesRendererProps<T extends string> {
  type: T;
  updates: PostGetUpdateReturn<T> | null;
  setIsModalVisible: (value: boolean) => void;
}

const UpdatesRenderer = <T extends string>({
  type,
  updates,
  setIsModalVisible
}: UpdatesRendererProps<T>) => {
  const navigation = useNavigation();
  const flashlistConfig = {
    waitForInteraction: true,
    itemVisiblePercentThreshold: 50,
    minimumViewTime: 1000
  };

  const handlePress = (item: any) => {
    setIsModalVisible(false);
    if (type === 'nm' || type === 'dare') {
      navigation.navigate(
        ...([
          NAVIGATION_PAGES.REGION_PREVIEW,
          {
            regionId: item.id,
            type: type === 'nm' ? 'nm' : 'dare',
            disabled: false,
            isProfileScreen: true
          }
        ] as never)
      );
    } else {
      navigation.navigate(
        ...([
          NAVIGATION_PAGES.COUNTRY_PREVIEW,
          {
            regionId: item.id,
            type: 'country',
            disabled: false,
            isProfileScreen: true
          }
        ] as never)
      );
    }
  };

  const renderContent = () => {
    if (!updates) return null;

    const renderHeader = (headerText: string) => (
      <RegionsModalHeader textHeader={headerText} onRequestClose={() => setIsModalVisible(false)} />
    );

    switch (type) {
      case 'nm':
        return (
          <>
            {renderHeader('Regions visited')}
            <FlashList
              viewabilityConfig={flashlistConfig}
              estimatedItemSize={50}
              data={(updates.data as NewNM).visited_regions}
              renderItem={({ item }) => (
                <TouchableOpacity onPress={() => handlePress(item)} style={styles.item}>
                  <Image
                    source={{
                      uri: API_HOST + '/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}
                  <Text style={styles.regionName}>{item.name}</Text>
                </TouchableOpacity>
              )}
              keyExtractor={(item, index) => item.id.toString() + index.toString()}
              showsVerticalScrollIndicator={false}
              nestedScrollEnabled={true}
              contentContainerStyle={{ paddingTop: 8 }}
            />
          </>
        );
      case 'un':
      case 'unp':
        return (
          <>
            {renderHeader('Countries visited')}
            <FlashList
              viewabilityConfig={flashlistConfig}
              estimatedItemSize={50}
              data={(updates.data as UnOrUnp).visited_countries}
              renderItem={({ item }) => (
                <TouchableOpacity onPress={() => handlePress(item)} style={styles.item}>
                  <Image
                    source={{
                      uri: API_HOST + '/img/flags_new/' + item.flag
                    }}
                    style={styles.regionsFlag}
                  />
                  <Text style={styles.regionName}>{item.country}</Text>
                </TouchableOpacity>
              )}
              keyExtractor={(item) => item.country.toString()}
              showsVerticalScrollIndicator={false}
              contentContainerStyle={{ paddingTop: 8 }}
            />
          </>
        );
      case 'dare':
        return (
          <>
            {renderHeader('New DAREs visited')}
            <FlashList
              viewabilityConfig={flashlistConfig}
              estimatedItemSize={50}
              data={updates.data as Dare[]}
              renderItem={({ item }) => (
                <TouchableOpacity style={styles.item} onPress={() => handlePress(item)}>
                  <Image
                    source={{
                      uri: API_HOST + '/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}
                  <Text style={styles.regionName}>{item.name}</Text>
                </TouchableOpacity>
              )}
              keyExtractor={(item) => item.id.toString()}
              showsVerticalScrollIndicator={false}
              contentContainerStyle={{ paddingTop: 8 }}
            />
          </>
        );
      case 'whs':
      case 'series':
        return (
          <>
            {renderHeader(type === 'whs' ? 'New WHS visited' : 'New Series visited')}
            <FlashList
              viewabilityConfig={flashlistConfig}
              estimatedItemSize={50}
              data={updates.data as SeriesOrWhs[]}
              renderItem={({ item }) => (
                <View style={styles.item}>
                  <Image
                    source={{
                      uri: API_HOST + item.app_icon
                    }}
                    style={{ width: 32, height: 32 }}
                  />
                  <Text style={[styles.regionName, { fontFamily: 'redhat-700' }]}>
                    {item.series}
                  </Text>
                  <Text style={[styles.regionName, { flex: 2 }]}>{item.item}</Text>
                </View>
              )}
              keyExtractor={(item, index) => item.item.toString() + index.toString()}
              showsVerticalScrollIndicator={false}
              contentContainerStyle={{ paddingTop: 8 }}
            />
          </>
        );
    }
  };

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

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

export default UpdatesRenderer;
