import { View, ActivityIndicator, Text } from "react-native";
import { useGetStates } from "../hooks/useGetStates";
import { ApiRequestStatus } from "../../common/const/api_request_states";
import {
  Caroussel
} from "../../common/components/caroussel/caroussel";
import { router } from "expo-router";
import { useAnimatedSelectedIndex } from "../../common/hooks/useAnimatedSelectedIndex";
import { AnimatedBackground } from "../../common/components/animated_background";
import { ErrorPage } from "../../common/screens/error_page";
import { LinearGradient } from "expo-linear-gradient";
import { LIGHT_THEME } from "../../common/const/theme";
import { useDataContext } from "../../common/contexts/data_context";
import { useAuth } from "../../auth/contexts/auth_context";
import { CARROUSEL_HEIGHT, CARROUSEL_WIDTH } from "../../common/const/caroussel";
import { pageStyles } from "../../common/styles/page_styles";

export const StateSelectionPage = () => {
  const { data, requestStatus, refresh } = useGetStates();
  const { selectedStateIndex, onIndexChange, backgroundImageAnimation } =
    useAnimatedSelectedIndex(200, 200);
  const { user } = useAuth();

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

  if (requestStatus === ApiRequestStatus.ERROR || !data) {
    return <ErrorPage refresh={refresh} />;
  }

  const handleOnPress = (id: number) => {
    router.push(`/state/${id}`);
  };

  return (
    <View style={{
      flex: 1,
      backgroundColor: LIGHT_THEME.color.background,
      alignItems: "center",
    }}>
      <Text style={{
        fontSize: 24,
        fontWeight: "bold",
        margin: 20,

      }}>
        {`Hola, ${user?.name} ${user?.lastName}!`}
      </Text>
      <View style={{ height: CARROUSEL_HEIGHT, width: CARROUSEL_WIDTH}}>
        <AnimatedBackground
          imageUri={data[selectedStateIndex].imageUri}
          backgroundImageAnimation={backgroundImageAnimation}
        />
        <LinearGradient
          colors={[
            LIGHT_THEME.color.background,
            "transparent",
            LIGHT_THEME.color.background,
          ]}
          locations={[0.1, 0.4, 0.9]}
          style={{
            position: "absolute",
            width: "100%",
            height: "100%",
          }}
        />
        <Caroussel
          data={data}
          onPress={handleOnPress}
          onIndexChange={onIndexChange}
        />
      </View>
    </View>
  );
};
