import { router } from "expo-router";
import { useState } from "react";
import { Alert, Text, TouchableOpacity, View } from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";

import { fetchAPI } from "@/lib/fetch";
import { useT } from "@/lib/i18n";
import { useSession } from "@/lib/session";

const RoleSelection = () => {
  const { setUserRole } = useSession();
  const t = useT();
  const [saving, setSaving] = useState(false);

  const chooseRole = async (role: "rider" | "driver") => {
    if (saving) return;

    setSaving(true);

    try {
      const { error } = await fetchAPI("/(api)/user", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ role }),
      });

      if (error) throw new Error(error);

      setUserRole(role);

      router.replace(
        role === "driver" ? "/(root)/driver-home" : "/(root)/(tabs)/home",
      );
    } catch (err) {
      console.log("[ROLE_SELECT]: ", err);
      Alert.alert(t("auth.role.alertErrorTitle"), t("auth.role.alertErrorBody"));
    } finally {
      setSaving(false);
    }
  };

  return (
    <SafeAreaView className="flex-1 bg-white dark:bg-neutral-950 justify-center px-7">
      <Text className="text-3xl font-JakartaExtraBold text-center text-black dark:text-white">
        {t("auth.role.title")}
      </Text>

      <Text className="text-base text-general-200 dark:text-neutral-400 font-Jakarta text-center mt-3 mb-10">
        {t("auth.role.subtitle")}
      </Text>

      <TouchableOpacity
        onPress={() => chooseRole("rider")}
        disabled={saving}
        className="bg-primary-500 rounded-2xl p-7 mb-5 items-center"
      >
        <Text className="text-5xl mb-3">🧍</Text>
        <Text className="text-2xl font-JakartaBold text-white">
          {t("auth.role.riderTitle")}
        </Text>
        <Text className="text-sm font-Jakarta text-white/80 text-center mt-2">
          {t("auth.role.riderDesc")}
        </Text>
      </TouchableOpacity>

      <TouchableOpacity
        onPress={() => chooseRole("driver")}
        disabled={saving}
        className="bg-general-600 dark:bg-primary-500/20 border border-primary-500 rounded-2xl p-7 items-center"
      >
        <Text className="text-5xl mb-3">🚗</Text>
        <Text className="text-2xl font-JakartaBold text-black dark:text-white">
          {t("auth.role.driverTitle")}
        </Text>
        <Text className="text-sm font-Jakarta text-general-200 dark:text-neutral-400 text-center mt-2">
          {t("auth.role.driverDesc")}
        </Text>
      </TouchableOpacity>
    </SafeAreaView>
  );
};

export default RoleSelection;