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

import { Header, PageWrapper } from '../../../../components';

import { ItemStyles } from '../../TravellersScreen/Components/styles';
import { API_HOST } from 'src/constants';
import { Colors } from 'src/theme';
import { NAVIGATION_PAGES } from 'src/types';
import { AccordionListItem } from './AccordionListItem';

const RegionsVisitedScreen = ({ route }: { route: any }) => {
  const title = route.params.title;
  const data = route.params.data ?? [];
  const isRegion = route.params.isRegion;
  const navigation = useNavigation();

  const [sorted, setSorted] = useState(data);
  const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('desc');
  const [expandedIds, setExpandedIds] = useState<number[]>([]);

  useEffect(() => {
    setSorted([...data].sort((a, b) => b.days_spent - a.days_spent));
    setSortDirection('desc');
  }, [data]);

  const sortList = () => {
    if (sortDirection === 'desc') {
      setSorted((prev: any) => [...prev].sort((a, b) => a.days_spent - b.days_spent));
      setSortDirection('asc');
    } else {
      setSorted((prev: any) => [...prev].sort((a, b) => b.days_spent - a.days_spent));
      setSortDirection('desc');
    }
  };

  const sortedRegions = (regions: { id: number; region: string; days_spent: number }[]) => {
    return regions.sort((a, b) => b.days_spent - a.days_spent);
  };

  return (
    <PageWrapper style={{ flex: 1 }}>
      <Header label={title} />
      {sorted ? (
        <FlatList
          contentContainerStyle={{ gap: 12, paddingBottom: 16 }}
          style={{ flex: 1 }}
          horizontal={false}
          data={sorted as any}
          keyExtractor={(item, index) => item.id.toString()}
          initialNumToRender={20}
          renderItem={({ item, index }) => {
            let subname = '';
            const [name, ...rest] = isRegion ? item.region?.split(/ – | - /) : ['', ''];
            if (isRegion) {
              subname = rest?.join(' - ');
            }

            return isRegion ? (
              <TouchableOpacity
                onPress={() =>
                  navigation.navigate(
                    ...([
                      NAVIGATION_PAGES.REGION_PREVIEW,
                      {
                        regionId: item.id,
                        isTravelsScreen: true,
                        type: 'nm',
                        disabled: false
                      }
                    ] as never)
                  )
                }
                style={[ItemStyles.wrapper, { paddingHorizontal: 8 }]}
              >
                <>
                  <Image
                    source={{
                      uri: API_HOST + item.flag1
                    }}
                    style={{
                      width: 32,
                      height: 32,
                      borderRadius: 32 / 2,
                      borderWidth: 1,
                      borderColor: Colors.FILL_LIGHT
                    }}
                  />
                  {item?.flag2 ? (
                    <Image
                      source={{ uri: API_HOST + item.flag2 }}
                      style={[
                        {
                          width: 32,
                          height: 32,
                          borderRadius: 32 / 2,
                          borderWidth: 1,
                          borderColor: Colors.FILL_LIGHT,
                          marginLeft: -18
                        }
                      ]}
                    />
                  ) : null}
                </>

                <View style={[ItemStyles.contentWrapper, { gap: 4 }]}>
                  <View style={{ flex: 1 }}>
                    <Text style={[{ color: Colors.DARK_BLUE, fontWeight: '600', fontSize: 15 }]}>
                      {name}
                    </Text>
                    {subname ? (
                      <Text style={[{ color: Colors.TEXT_GRAY, fontSize: 13 }]}>{subname}</Text>
                    ) : null}
                  </View>

                  <Text
                    style={[
                      ItemStyles.nameAndCnt,
                      { fontFamily: 'montserrat-700', fontSize: 15, paddingHorizontal: 4 }
                    ]}
                  >
                    {item.days_spent}
                  </Text>
                </View>
              </TouchableOpacity>
            ) : (
              <AccordionListItem
                id={item.id}
                altId={item.alt_id}
                name={item.country}
                daysSpent={item.days_spent}
                flag={item.flag}
                regions={sortedRegions(item.regions)}
                navigation={navigation}
                expandedIds={expandedIds}
                setExpandedIds={setExpandedIds}
              />
            );
          }}
          showsVerticalScrollIndicator={false}
          ListHeaderComponent={
            <View
              style={{
                flexDirection: 'row',
                justifyContent: 'space-between',
                alignItems: 'center'
              }}
            >
              <TouchableOpacity
                onPress={sortList}
                style={{
                  paddingHorizontal: 12,
                  paddingVertical: 6,
                  borderRadius: 6,
                  borderColor: Colors.DARK_BLUE,
                  borderWidth: 1
                }}
              >
                <Text style={{ color: Colors.DARK_BLUE, fontWeight: '600', fontSize: 13 }}>
                  {sortDirection === 'desc' ? 'Sort ↑' : 'Sort ↓'}
                </Text>
              </TouchableOpacity>

              <Text style={{ color: Colors.DARK_BLUE, fontWeight: '600', fontSize: 13 }}>
                Days spent
              </Text>
            </View>
          }
        />
      ) : null}
    </PageWrapper>
  );
};

export default RegionsVisitedScreen;
