import { View, StyleSheet, Text, FlatList } from "react-native";
import { useGenerateRoute } from "../hooks/useGenerateRoute";
import { ApiRequestStatus } from "../../common/const/api_request_states";
import { FullPageLoader } from "../../common/components/full_page_loader";
import { RouteActivityTile } from "../components/route_activity_tile";
import { TouchableOpacity } from "react-native-gesture-handler";
import { router } from "expo-router";
import { LIGHT_THEME } from "../../common/const/theme";
import { FloatingBackButton } from "../../common/components/floating_back_button";
import { FloatingEndActionButton } from "../../common/components/floating_end_action_button";
import { useGet } from "../../common/hooks/useGet";
import { useGetRoute } from "../hooks/useGetRoute";
import { useDataContext } from "../../common/contexts/data_context";
import { usePreviewRoute } from "../hooks/usePreviewRoute";
import { formatToDDMMYYYY } from "../../common/utils/time";

interface RoutePreviewPageProps {
  townId: number;
}

export const RoutePreviewPage = ({
  townId: routeId,
}: RoutePreviewPageProps) => {
  const {
    route,
    saveRoute,
    mainRequestStatus: requestStatus,
  } = usePreviewRoute(routeId);

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

  if (requestStatus === ApiRequestStatus.ERROR || !route) {
    return <Text>Something went wrong</Text>;
  }

  return (
    <View style={styles.main_container}>
      <FloatingBackButton />
      <FlatList
        data={route.travelPlaces}
        style={styles.container}
        ListHeaderComponent={() => (
          <View
            style={{ height: 150, paddingVertical: 10, paddingHorizontal: 20 }}
          >
            <Text
              style={{ fontSize: 25, fontWeight: "bold", alignSelf: "center" }}
            >
              Route Preview
            </Text>
            <Text
              style={{ fontSize: 15, marginTop: 30 }}
            >{`Start: ${formatToDDMMYYYY(route.startDate)}`}</Text>
            <Text
              style={{ fontSize: 15, marginTop: 10 }}
            >{`End: ${formatToDDMMYYYY(route.endDate)}`}</Text>
          </View>
        )}
        renderItem={({ item, index }) => {
          const isFirst = index === 0;
          const isLast = index === route.travelPlaces.length - 1;
          return (
            <RouteActivityTile
              activity={item}
              isFirst={isFirst}
              isLast={isLast}
            />
          );
        }}
        keyExtractor={(item, index) => index.toString()}
        ListFooterComponent={() => <View style={{ height: 100 }} />}
      />
      <FloatingEndActionButton onPress={saveRoute} title="Save Route" />
    </View>
  );
};

const styles = StyleSheet.create({
  main_container: {
    flex: 1,
  },
  container: {
    flex: 1,
    width: "100%",
    backgroundColor: "#fff",
    padding: 10,
  },
});
