import React, { useCallback, useEffect, 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 TripItem from '../Components/TripItem';

import { useGetTripsYearsQuery, useGetTripsForYearQuery } 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';

const TripsScreen = ({ route }: { route: any }) => {
  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>(null);
  const { data: tripsData, refetch: refetchTrips } = useGetTripsForYearQuery(
    token,
    selectedYear as string,
    selectedYear ? true : false
  );
  const [trips, setTrips] = useState<TripsData[]>([]);
  const [isWarningModalVisible, setIsWarningModalVisible] = useState(false);

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

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

  useEffect(() => {
    if (years && years.data && !selectedYear) {
      setSelectedYear(years.data[0]);
    }
  }, [years]);

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

  useEffect(() => {
    if (tripsData && tripsData.trips) {
      setTrips(tripsData.trips);
    }
  }, [tripsData]);

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

  const onAddNewTripPress = useCallback(() => {
    navigation.navigate(NAVIGATION_PAGES.ADD_TRIP as never);
  }, [navigation]);

  return (
    <PageWrapper>
      <Header
        label="Trips"
        // rightElement={
        //   <TouchableOpacity
        //     onPress={() => navigation.navigate(NAVIGATION_PAGES.TRIPS_INFO as never)}
        //     style={{ width: 30 }}
        //   >
        //     <InfoIcon />
        //   </TouchableOpacity>
        // }
      />
      <View style={styles.tabContainer}>
        <TouchableOpacity style={styles.regionSelector} onPress={() => setDatePickerVisible(true)}>
          <Text style={[styles.regionText]}>{selectedYear}</Text>
          <ChevronIcon />
        </TouchableOpacity>
        <TouchableOpacity style={styles.addNewTab} onPress={onAddNewTripPress}>
          <AddIcon />
          <Text style={styles.addNewTabText}>Add New Trip</Text>
        </TouchableOpacity>
      </View>

      {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>
      ) : (
        <FlatList
          data={trips}
          renderItem={renderItem}
          keyExtractor={(item, index) => `${item.id}-${index}`}
          style={styles.tripsList}
          contentContainerStyle={styles.tripsListContentContainer}
          showsVerticalScrollIndicator={false}
        />
      )}

      <Modal
        onRequestClose={() => setDatePickerVisible(false)}
        headerTitle={'Select Year'}
        visible={isDatePickerVisible}
      >
        <List
          itemObject={(object) => {
            setSelectedYear(object);
            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'
        }
      />
    </PageWrapper>
  );
};

export default TripsScreen;
