import { View, Text, ActivityIndicator, StyleSheet } from "react-native";
import { pageStyles } from "../page_styles";
import { useGetStates } from "../../hooks/useGetStates";
import { ApiRequestStatus } from "../../constants/api_request_states";
import { Caroussel } from "../../components/caroussel/caroussel";
import { useGetTowns } from "../../hooks/useGetTowns";
import { router } from "expo-router";
import { useCallback, useState } from "react";
import { useAnimatedSelectedIndex } from "../../hooks/useAnimatedSelectedIndex";
import { AnimatedBackground } from "../../components/animated_background/animated_background";
import BottomSheet, { BottomSheetView } from "@gorhom/bottom-sheet";

interface TownSelectionPageProps {
  stateId: number;
}

const snapPoints = ["15%", "50%"];

export const TownSelectionPage = ({ stateId }: TownSelectionPageProps) => {
  const { data, requestStatus } = useGetTowns(stateId);
  const { selectedStateIndex, onIndexChange, backgroundImageAnimation } =
    useAnimatedSelectedIndex(200, 200);

  if (requestStatus === ApiRequestStatus.LOADING) {
    return (
      <View style={pageStyles.page_container}>
        <ActivityIndicator size="large" color="#0000ff" />
      </View>
    );
  }

  if (data.length === 0) {
    return (
      <View style={pageStyles.page_container}>
        <Text>No towns found</Text>
      </View>
    );
  }

  const handleTownSelection = (townId: number) => {
    router.push(`/state/${stateId}/town/${townId}`);
  };

  return (
    <View style={pageStyles.page_container}>
      <AnimatedBackground
        imageUri={data[selectedStateIndex].imageUri}
        backgroundImageAnimation={backgroundImageAnimation}
      />
      <Caroussel
        data={data}
        onPress={handleTownSelection}
        onIndexChange={onIndexChange}
      />
      {data[selectedStateIndex].description && (
        <BottomSheet snapPoints={snapPoints}>
          <BottomSheetView style={styles.container}>
            <Text style={styles.description_text}>Description</Text>
            <Text>{data[selectedStateIndex].description}</Text>
          </BottomSheetView>
        </BottomSheet>
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingHorizontal: 20,
    gap: 20,
  },
  description_text: {
    fontSize: 20,
    fontWeight: "bold",
  },
  description_content_text: {
    fontSize: 16,
  },
});
