import React, { useEffect, useState } from 'react';
import { FlatList, Text, TouchableOpacity, View } from 'react-native';
import { Image } from 'expo-image';

import {
  Header,
  HorizontalTabView,
  Loading,
  PageWrapper,
  WarningModal
} from '../../../../components';
import {
  getMastersByCountryOfOrigin,
  getMastersByType,
  getMastersByYearOfCompletion,
  getUNMastersTypes
} from '../../../../database/unMastersService';
import { API_HOST } from '../../../../constants';

import { UNMastersListStyles } from './styles';

import type { Master } from '../../../../database/unMastersService';
import { Colors } from '../../../../theme';
import { getFontSize } from '../../../../utils';
import { useNavigation } from '@react-navigation/native';
import { NAVIGATION_PAGES } from 'src/types';
import { FlashList } from '@shopify/flash-list';
import { SafeAreaView } from 'react-native-safe-area-context';

const UNMastersScreen = () => {
  const [index, setIndex] = useState(0);
  const [routes, setRoutes] = useState<{ key: string; title: string }[]>([]);
  const [loading, setLoading] = useState(true);
  const navigation = useNavigation();

  useEffect(() => {
    const types = getUNMastersTypes();

    const parseRoutes = types?.map((item) => ({
      key: item.type.toString(),
      title: item.name
    }));

    setRoutes([
      { key: '-1', title: 'Sorted by country of origin' },
      { key: '-2', title: 'Sorted by year of completion' },
      ...(parseRoutes || [])
    ]);
    setLoading(false);
  }, []);

  if (loading) return <Loading />;

  return (
    <SafeAreaView style={{ height: '100%' }} edges={['top']}>
      <View style={{ marginLeft: '5%', marginRight: '5%' }}>
        <Header label={'UN Masters'} />
      </View>
      <HorizontalTabView
        index={index}
        setIndex={setIndex}
        lazy={true}
        routes={routes}
        maxTabHeight={50}
        renderScene={({ route }: { route: { key: string; title: string } }) => (
          <UNMastersList type={route.key} navigation={navigation} />
        )}
      />
    </SafeAreaView>
  );
};

const UNMastersList = React.memo(({ type, navigation }: { type: string; navigation: any }) => {
  const [isLoading, setIsLoading] = useState(true);
  const [modalVisible, setModalVisible] = useState(false);
  const [masters, setMasters] = useState<
    | Master[]
    | { country: string; count: number; masters: Master[] }[]
    | { year: string; count: number; masters: Master[] }[]
    | null
  >([]);

  useEffect(() => {
    const fetchType = async () => {
      if (type === '-2') {
        const data = getMastersByYearOfCompletion();
        setMasters(data);
      } else if (type === '-1') {
        const data = getMastersByCountryOfOrigin();
        setMasters(data);
      } else {
        const data = getMastersByType(Number(type) || 1);
        setMasters(data);
      }
    };

    fetchType();
    setIsLoading(false);
  }, [type]);

  if (isLoading) return <Loading />;

  const handlePress = (userId: number | null) => {
    if (userId) {
      navigation.navigate(NAVIGATION_PAGES.PUBLIC_PROFILE_VIEW, {
        userId
      } as never);
    } else {
      setModalVisible(true);
    }
  };

  const renderItem = ({ item }: { item: any }) => {
    const UserItem = ({ user }: { user: Master }) => {
      return (
        <TouchableOpacity
          style={[
            UNMastersListStyles.wrapper,
            { backgroundColor: Colors.FILL_LIGHT, borderRadius: 8, padding: 6, marginVertical: 5 }
          ]}
          onPress={() => handlePress(user.user_id)}
        >
          <View style={{ gap: 3, marginLeft: 5 }}>
            <Text style={UNMastersListStyles.firstAndLastName}>{user.full_name}</Text>
            <View style={[UNMastersListStyles.wrapper, { marginBottom: 0 }]}>
              <Text style={UNMastersListStyles.descriptionText}>
                Born: {user.born} / Age when done: {user.age} /
              </Text>
              <Image
                style={[UNMastersListStyles.countryFlag, { marginLeft: 5 }]}
                source={{ uri: API_HOST + '/img/flags_new/' + user.origin1_flag }}
              />
              {user.origin2_flag && user.origin2_flag !== user.origin1_flag ? (
                <Image
                  style={[UNMastersListStyles.countryFlag, { marginLeft: -5 }]}
                  source={{ uri: API_HOST + '/img/flags_new/' + user.origin2_flag }}
                />
              ) : null}
            </View>
            <View style={[UNMastersListStyles.wrapper, { marginBottom: 0 }]}>
              <Text style={UNMastersListStyles.descriptionText}>
                Year / final country: {user.final_year}
              </Text>
              <Image
                style={[UNMastersListStyles.countryFlag, { marginLeft: 5 }]}
                source={{ uri: API_HOST + '/img/flags_new/' + user.final_flag }}
              />
            </View>
          </View>
        </TouchableOpacity>
      );
    };

    const CountryItem = ({
      country,
      masters,
      count
    }: {
      country: string;
      masters: Master[];
      count: number;
    }) => {
      if (masters.length === 0) return;

      return (
        <View style={[UNMastersListStyles.countryAndYearItemWrapper, { marginVertical: 5 }]}>
          <View style={UNMastersListStyles.countryAndYearHeader}>
            <Text style={{ color: Colors.DARK_BLUE, fontSize: getFontSize(18), fontWeight: '700' }}>
              {country} ({count})
            </Text>
          </View>
          <FlatList
            scrollEnabled={false}
            horizontal={false}
            showsVerticalScrollIndicator={false}
            data={masters}
            renderItem={({ item }) => <UserItem user={item} />}
          />
        </View>
      );
    };

    const YearItem = ({
      year,
      masters,
      count
    }: {
      year: string;
      masters: Master[];
      count: number;
    }) => {
      return (
        <View style={[UNMastersListStyles.countryAndYearItemWrapper, { marginVertical: 5 }]}>
          <View style={UNMastersListStyles.countryAndYearHeader}>
            <Text style={{ color: Colors.DARK_BLUE, fontSize: getFontSize(18), fontWeight: '700' }}>
              {year} ({count})
            </Text>
          </View>
          <FlatList
            scrollEnabled={false}
            horizontal={false}
            showsVerticalScrollIndicator={false}
            data={masters}
            renderItem={({ item }) => <UserItem user={item} />}
          />
        </View>
      );
    };

    return type !== '-2' ? (
      type !== '-1' ? (
        <UserItem user={item as Master} />
      ) : (
        <CountryItem country={item.country} masters={item.masters} count={item.count} />
      )
    ) : (
      <YearItem year={item.year} masters={item.masters} count={item.count} />
    );
  };

  return (
    <>
      <FlashList
        viewabilityConfig={{
          waitForInteraction: true,
          itemVisiblePercentThreshold: 50,
          minimumViewTime: 1000
        }}
        estimatedItemSize={100}
        horizontal={false}
        data={masters}
        renderItem={renderItem}
        showsVerticalScrollIndicator={false}
      />
      <WarningModal
        type="success"
        isVisible={modalVisible}
        onClose={() => setModalVisible(false)}
        message="This person does not have a profile on NomadMania."
      />
    </>
  );
});

export default UNMastersScreen;
