import React, { useCallback, useEffect, useState } from 'react';
import { View, Text, FlatList, Image, TouchableOpacity } from 'react-native';
import { useNavigation } from '@react-navigation/native';

import { Header, PageWrapper, HorizontalTabView, Loading, WarningModal } from 'src/components';
import { useGetSeriesGroups, useGetSeriesWithGroup } from '@api/series';
import { useFocusEffect } from '@react-navigation/native';

import { API_HOST } from 'src/constants';
import { StoreType, storage } from 'src/storage';
import { styles } from './styles';
import { NAVIGATION_PAGES } from 'src/types';
import AddSvg from 'assets/icons/travels-section/add.svg';
import { SafeAreaView } from 'react-native-safe-area-context';

interface SeriesGroup {
  key: string;
  title: string;
}

interface SeriesList {
  id: number;
  name: string;
  icon: string;
  count: number;
  new: number;
  score: number;
  icon_png: string;
  count2: number;
}

const SeriesScreen = () => {
  const token = storage.get('token', StoreType.STRING) as string;
  const [isLoading, setIsLoading] = useState(true);
  const [index, setIndex] = useState(0);
  const [routes, setRoutes] = useState<SeriesGroup[]>([]);
  const [warningVisible, setWarningVisible] = useState(false);
  const { data } = useGetSeriesGroups(true);
  const navigation = useNavigation();

  useFocusEffect(
    useCallback(() => {
      const fetchGroups = async () => {
        let staticGroups = [
          {
            key: '-1',
            title: 'Top of the tops'
          },
          {
            key: '-2',
            title: 'Milestones'
          },
          {
            key: 'all',
            title: 'All series'
          }
        ];
        const routesData = data?.data?.map((item) => ({
          key: item.id.toString(),
          title: item.name
        }));

        routesData && staticGroups.push(...routesData);

        setRoutes(staticGroups);
        setIsLoading(false);
      };

      if (data && data.data) {
        fetchGroups();
      }
    }, [data])
  );

  if (isLoading) return <Loading />;

  return (
    <SafeAreaView style={{ height: '100%' }} edges={['top']}>
      <View style={{ marginLeft: '5%', marginRight: '5%' }}>
        <Header
          label={'Series'}
          rightElement={
            <TouchableOpacity
              onPress={() => {
                if (token) {
                  navigation.navigate(NAVIGATION_PAGES.SUGGEST_SERIES as never);
                } else {
                  setWarningVisible(true);
                }
              }}
            >
              <AddSvg />
            </TouchableOpacity>
          }
        />
      </View>

      <HorizontalTabView
        index={index}
        setIndex={setIndex}
        routes={routes}
        maxTabHeight={50}
        renderScene={({ route }: { route: SeriesGroup }) => (
          <SeriesList groupId={route.key} navigation={navigation} />
        )}
      />
      <WarningModal
        type="unauthorized"
        isVisible={warningVisible}
        onClose={() => setWarningVisible(false)}
      />
    </SafeAreaView>
  );
};

const SeriesList = React.memo(({ groupId, navigation }: { groupId: string; navigation: any }) => {
  const [seriesData, setSeriesData] = useState<SeriesList[]>([]);
  const [isLoading, setIsLoading] = useState(true);

  const token = storage.get('token', StoreType.STRING) as string;
  const { mutateAsync } = useGetSeriesWithGroup();

  useEffect(() => {
    const fetchSeriesData = async () => {
      try {
        await mutateAsync(
          { group: groupId, token: String(token) },
          {
            onSuccess: (data) => {
              setSeriesData(data.data);
            }
          }
        );
      } catch (error) {
        console.error('Failed to fetch series data', error);
      } finally {
        setIsLoading(false);
      }
    };

    fetchSeriesData();
  }, [groupId]);

  if (isLoading) return <Loading />;

  const renderItem = ({ item }: { item: SeriesList }) => {
    return (
      <TouchableOpacity
        style={styles.itemContainer}
        onPress={() =>
          navigation.navigate(NAVIGATION_PAGES.SERIES_ITEM, { id: item.id, name: item.name, token })
        }
      >
        <Image style={styles.icon} source={{ uri: API_HOST + item.icon_png }} />

        <View style={styles.infoContainer}>
          <View style={styles.titleContainer}>
            <Text style={styles.title}>{item.name}</Text>
            {item.new === 1 && <Text style={styles.textNew}>NEW</Text>}
          </View>

          <View style={styles.detailsContainer}>
            <Text style={styles.details}>Total objects: {item.count}</Text>
            <Text style={styles.count}>
              {token ? item.score : 0} / {item.count}
            </Text>
          </View>
        </View>
      </TouchableOpacity>
    );
  };

  return (
    <FlatList
      horizontal={false}
      data={seriesData}
      renderItem={renderItem}
      keyExtractor={(item) => item.id.toString()}
      showsVerticalScrollIndicator={false}
    />
  );
});

export default SeriesScreen;
