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

import { PageWrapper, Header, Modal, FlatList as List, WarningModal } from 'src/components';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import TripItem from '../Components/TripItem';

import {
  useGetTripsYearsQuery,
  useGetTripsForYearQuery,
  useGetTripsForRegionQuery,
  useGetRegionsThatHaveTripsQuery
} from '@api/trips';
import { StoreType, storage } from 'src/storage';
import { TripsData } from '../utils/types';
import { NAVIGATION_PAGES } from 'src/types';
import { styles } from './styles';

import ChevronIcon from '../../../../../assets/icons/travels-screens/chevron-bottom.svg';
import AddIcon from '../../../../../assets/icons/travels-screens/circle-plus.svg';
import TripSvg from '../../../../../assets/icons/travels-screens/trip.svg';
import InfoIcon from 'assets/icons/info-solid.svg';
import { Colors } from 'src/theme';
import ChevronLeftIcon from 'assets/icons/chevron-left.svg';
import { getFontSize } from 'src/utils';
import { FlashList, FlashListRef } from '@shopify/flash-list';
import WarningIcon from 'assets/icons/warning.svg';
import moment from 'moment';
import ChevronLeft from 'assets/icons/chevron-left.svg';

const TripsScreen = ({ route }: { route: any }) => {
  const insets = useSafeAreaInsets();
  const token = storage.get('token', StoreType.STRING) as string;
  const navigation = useNavigation();
  const [isDatePickerVisible, setDatePickerVisible] = useState(false);
  const { data: years, refetch } = useGetTripsYearsQuery(token, true);
  const [selectedYear, setSelectedYear] = useState<string | null>(
    !route.params?.region ? moment().year().toString() : null
  );
  const [selectedRegion, setSelectedRegion] = useState<{ id: number; name: string } | null>(
    route.params?.region
      ? { id: route.params?.region?.id, name: route.params?.region?.name ?? '' }
      : null
  );
  const { data: tripsData, refetch: refetchTrips } = useGetTripsForYearQuery(
    token,
    selectedYear as string,
    selectedYear ? true : false
  );
  const { data: tripsDataForRegion, refetch: refetchTripsForRegion } = useGetTripsForRegionQuery(
    token,
    selectedRegion ? selectedRegion.id : -1,
    selectedRegion ? true : false
  );
  const { data: regionsThatHaveTrips, refetch: refetchRegionsThatHaveTrips } =
    useGetRegionsThatHaveTripsQuery(true);
  const [trips, setTrips] = useState<TripsData[]>([]);
  const [statistics, setStatistics] = useState<{
    countries: {
      description: string;
      list: {
        id: number;
        alt_id: number | null;
        country: string;
        days_spent: number;
        flag: string | null;
        regions: {
          id: number;
          region: string;
          days_spent: number;
        }[];
      }[];
    };
    general: [string];
    regions: {
      description: string;
      list: {
        id: number;
        days_spent: number;
        flag: string | null;
        flag1: string | null;
        flag2: string | null;
        region: string;
      }[];
    };
    dates_missing: 0 | 1;
  } | null>(null);
  const [isWarningModalVisible, setIsWarningModalVisible] = useState(false);
  const [isModalVisible, setIsModalVisible] = useState(false);

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

  useFocusEffect(
    useCallback(() => {
      const fetchData = async () => {
        try {
          await refetch();
          if (selectedYear) {
            await refetchTrips();
          }
          if (selectedRegion) {
            await refetchTripsForRegion();
          }
          await refetchRegionsThatHaveTrips();
        } catch (error) {
          console.error(error);
        }
      };

      if (route.params?.saved || route.params?.updated || route.params?.deleted) {
        fetchData();
        setIsWarningModalVisible(true);
      }
    }, [route.params])
  );

  useEffect(() => {
    if (route?.params?.region) {
      navigation.getParent()?.setOptions({
        tabBarStyle: {
          display: 'flex'
        }
      });
    }
  }, [route]);

  useEffect(() => {
    if (!isWarningModalVisible) {
      navigation.setParams({ saved: false, updated: false, deleted: false } as never);
    }
  }, [isWarningModalVisible]);

  useEffect(() => {
    if (tripsData && tripsData.trips && !selectedRegion) {
      setStatistics(tripsData.statistics ?? null);
      setTrips(tripsData.trips);
    }
  }, [tripsData, selectedRegion]);

  useEffect(() => {
    if (tripsDataForRegion && tripsDataForRegion.trips && selectedRegion) {
      setStatistics(null);
      setTrips(tripsDataForRegion.trips ?? []);
    }
  }, [tripsDataForRegion, selectedRegion]);

  const renderItem = useCallback(
    ({ item }: { item: TripsData }) => <TripItem item={item} />,
    [statistics]
  );

  const onAddNewTripPress = useCallback(() => {
    navigation.navigate(
      ...([
        NAVIGATION_PAGES.ADD_TRIP_2025,
        {
          defaultRegion: selectedRegion,
          defaultYear: selectedYear
        }
      ] as never)
    );
  }, [navigation, selectedYear, selectedRegion]);

  const handleScrollToTrip = () => {
    if (!flashListRef?.current) return;

    const index = trips.findIndex((trip) => trip.dates_missing === 1);

    if (index === -1) return;

    flashListRef.current.scrollToIndex({
      index,
      animated: true,
      viewPosition: 0
    });
  };

  return (
    <View style={{ paddingTop: insets.top, marginLeft: '5%', marginRight: '5%', height: '100%' }}>
      <View
        style={{
          display: 'flex',
          flexDirection: 'row',
          alignItems: 'center',
          justifyContent: 'space-between',
          width: '100%',
          paddingVertical: 16
        }}
      >
        {route.params?.region ? (
          <TouchableOpacity onPress={() => navigation.goBack()}>
            <View
              style={{
                width: 25,
                height: 25,
                display: 'flex',
                justifyContent: 'center',
                alignItems: 'center'
              }}
            >
              <ChevronLeft fill={Colors.DARK_BLUE} />
            </View>
          </TouchableOpacity>
        ) : (
          <View style={{ width: 25, height: 25 }} />
        )}
        <Text
          style={{ color: Colors.DARK_BLUE, fontFamily: 'redhat-700', fontSize: getFontSize(14) }}
        >
          Trips
        </Text>
        <View style={{ width: 25, height: 25 }} />
      </View>
      <View style={styles.tabContainer}>
        <TouchableOpacity style={styles.regionSelector} onPress={() => setDatePickerVisible(true)}>
          <Text style={[styles.regionText]}>{selectedYear ?? 'All years'}</Text>
          <ChevronIcon />
        </TouchableOpacity>
        <TouchableOpacity style={styles.addNewTab} onPress={onAddNewTripPress}>
          <AddIcon />
          <Text style={styles.addNewTabText}>Add New Trip</Text>
        </TouchableOpacity>
      </View>

      <TouchableOpacity
        style={[styles.regionSelector, { flex: 0, marginBottom: 6 }]}
        onPress={() => setIsModalVisible(true)}
      >
        <Text style={[styles.regionText, { flex: 1 }]} numberOfLines={1}>
          {selectedRegion ? selectedRegion.name : 'All regions'}
        </Text>
        <ChevronIcon />
      </TouchableOpacity>

      {trips.length === 0 ? (
        <View style={styles.noTripsContainer}>
          <View style={styles.noTripsIcon}>
            <TripSvg fill={Colors.WHITE} />
          </View>
          <Text style={styles.noTripsText}>No trips at the moment</Text>
        </View>
      ) : (
        <FlashList
          ref={flashListRef}
          data={trips}
          renderItem={renderItem}
          keyExtractor={(item, index) => `${item.id}-${index}`}
          style={styles.tripsList}
          contentContainerStyle={styles.tripsListContentContainer}
          showsVerticalScrollIndicator={false}
          ListHeaderComponent={
            statistics ? (
              <View
                style={{
                  marginTop: 12,
                  marginBottom: 8,
                  backgroundColor: Colors.FILL_LIGHT,
                  borderRadius: 8,
                  paddingHorizontal: 16,
                  paddingVertical: 12,
                  gap: 6
                }}
              >
                {statistics?.general ? (
                  <Text style={{ fontSize: 14, fontWeight: '600', color: Colors.DARK_BLUE }}>
                    {statistics.general}
                  </Text>
                ) : null}

                <TouchableOpacity
                  onPress={() =>
                    navigation.navigate(
                      ...([
                        NAVIGATION_PAGES.REGIONS_VISITED,
                        {
                          title: statistics?.countries?.description,
                          isRegion: false,
                          data: statistics?.countries?.list
                        }
                      ] as never)
                    )
                  }
                  hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }}
                >
                  <Text style={{ fontSize: 14, fontWeight: '600', color: Colors.ORANGE }}>
                    {statistics?.countries?.description}
                  </Text>
                </TouchableOpacity>

                <TouchableOpacity
                  onPress={() =>
                    navigation.navigate(
                      ...([
                        NAVIGATION_PAGES.REGIONS_VISITED,
                        {
                          title: statistics?.regions?.description,
                          isRegion: true,
                          data: statistics?.regions?.list
                        }
                      ] as never)
                    )
                  }
                  hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }}
                >
                  <Text style={{ fontSize: 14, fontWeight: '600', color: Colors.ORANGE }}>
                    {statistics?.regions?.description}
                  </Text>
                </TouchableOpacity>

                {statistics?.dates_missing ? (
                  <TouchableOpacity
                    onPress={handleScrollToTrip}
                    hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }}
                    style={{ marginTop: 8, flexDirection: 'row', gap: 8, alignItems: 'center' }}
                  >
                    <WarningIcon color={Colors.RED} width={20} height={20} />
                    <Text style={{ fontSize: 14, fontWeight: '600', color: Colors.RED, flex: 1 }}>
                      For accurate annual statistics, please enter exact dates for all trips.
                    </Text>
                  </TouchableOpacity>
                ) : null}
              </View>
            ) : null
          }
        />
      )}

      <Modal
        onRequestClose={() => setDatePickerVisible(false)}
        headerTitle={'Select Year'}
        visible={isDatePickerVisible}
      >
        <List
          itemObject={(object) => {
            setSelectedYear(object);
            setSelectedRegion(null);
            setDatePickerVisible(false);
          }}
          initialData={years?.data}
          date={true}
        />
      </Modal>
      <WarningModal
        type={'success'}
        isVisible={isWarningModalVisible}
        onClose={() => {
          setIsWarningModalVisible(false);
        }}
        title={
          route.params?.saved
            ? 'Trip added'
            : route.params?.deleted
              ? 'Trip deleted'
              : 'Trip updated'
        }
        message={
          route.params?.saved
            ? 'Trip was successfully added to your list of trips'
            : route.params?.deleted
              ? 'This trip was successfully deleted.'
              : 'Trip was successfully updated'
        }
      />

      <Modal
        onRequestClose={() => setIsModalVisible(false)}
        headerTitle={'Select Region'}
        visible={isModalVisible}
      >
        <List
          filteredRegions={regionsThatHaveTrips?.data ?? []}
          itemObject={(object) => {
            setIsModalVisible(false);
            setSelectedRegion(object);
            setSelectedYear(null);
          }}
        />
      </Modal>
    </View>
  );
};

export default TripsScreen;
