import { View, Text, FlatList, StyleSheet, SectionList } from "react-native";
import {
  TravelHistorySection,
  useGetTravelHistory,
} from "../../travel/hooks/useGetTravelHistory";
import { ApiRequestStatus } from "../../common/const/api_request_states";
import { FullPageLoader } from "../../common/components/full_page_loader";
import { CustomTileButton } from "../../common/components/custom_tile_button";
import { LIGHT_THEME } from "../../common/const/theme";
import { router, useFocusEffect } from "expo-router";
import { formatToDDMMYYYY } from "../../common/utils/time";
import { useEffect, useRef } from "react";

export const TravelHistoryPage = () => {
  const { travelHistory, requestStatus, refresh } = useGetTravelHistory();
  const reloadNeeded = useRef(true);

  useFocusEffect(() => {
    if (reloadNeeded.current) {
      reloadNeeded.current = false;
      refresh();
    }
  });

  const onTresholdReached = () => {
    refresh();
  };

  if (requestStatus === ApiRequestStatus.LOADING) {
    return <FullPageLoader />;
  }

  if (requestStatus === ApiRequestStatus.ERROR || !travelHistory) {
    return (
      <View>
        <Text>Error</Text>
      </View>
    );
  }

  const onPressPastTravel = (id: number) => {
    reloadNeeded.current = true;
    router.push(`/travel_history/details/${id}`);
  };

  const onPressActiveTravel = (id: number) => {
    reloadNeeded.current = true;
    router.push(`/travel_history/active/${id}`);
  };

  return (
    <SectionList
      sections={travelHistory}
      scrollEnabled={true}
      keyExtractor={(item, index) => item.id.toString() + index}
      renderItem={({ item, section }) => {
        switch (section.type) {
          case TravelHistorySection.ACTIVE:
            return (
              <CustomTileButton
                title={item.destination}
                subtitle={`${formatToDDMMYYYY(
                  item.startDate
                )} - ${formatToDDMMYYYY(item.endDate)}`}
                onPress={() => onPressActiveTravel(item.id)}
              />
            );
          default:
            return (
              <CustomTileButton
                title={item.destination}
                subtitle={`${formatToDDMMYYYY(
                  item.startDate
                )} - ${formatToDDMMYYYY(item.endDate)}`}
                onPress={() => onPressPastTravel(item.id)}
              />
            );
        }
      }}
      renderSectionHeader={({ section: { title } }) => (
        <View style={styles.pastTravelsHeaderContainer}>
          <Text style={styles.pastTravelsHeaderTitle}>{title}</Text>
        </View>
      )}
      style={styles.pastTravelsContainer}
      ListFooterComponent={<View style={{ height: 50 }} />}
      ItemSeparatorComponent={() => <View style={{ height: 10 }} />}
      renderSectionFooter={({ section }) => {
        if (section.data.length === 0) {
          return (
            <View style={{ alignItems: "center" }}>
              <Text>No travels</Text>
            </View>
          );
        }
        return null;
      }}
    />
  );
};

const styles = StyleSheet.create({
  pastTravelsHeaderContainer: {
    width: "100%",
    height: 50,
    backgroundColor: LIGHT_THEME.color.background,
    marginBottom: 15,
    justifyContent: "center",
    alignItems: "center",
  },
  pastTravelsHeaderTitle: {
    fontSize: 18,
    fontWeight: "600",
  },
  pastTravelsContainer: {
    flex: 1,
    backgroundColor: LIGHT_THEME.color.background,
    paddingHorizontal: 15,
  },
});
