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 { useSession } from "@/lib/session";

const RoleSelection = () => {
  const { setUserRole } = useSession();
  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("Error", "Could not save your choice. Please try again.");
    } finally {
      setSaving(false);
    }
  };

  return (
    <SafeAreaView className="flex-1 bg-white justify-center px-7">
      <Text className="text-3xl font-JakartaExtraBold text-center">
        How will you use Waseel?
      </Text>

      <Text className="text-base text-general-200 font-Jakarta text-center mt-3 mb-10">
        You can change this later by contacting support.
      </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">
          I&apos;m a Rider
        </Text>
        <Text className="text-sm font-Jakarta text-white/80 text-center mt-2">
          Book rides and get around Lebanon
        </Text>
      </TouchableOpacity>

      <TouchableOpacity
        onPress={() => chooseRole("driver")}
        disabled={saving}
        className="bg-general-600 rounded-2xl p-7 items-center"
      >
        <Text className="text-5xl mb-3">🚗</Text>
        <Text className="text-2xl font-JakartaBold">I&apos;m a Driver</Text>
        <Text className="text-sm font-Jakarta text-general-200 text-center mt-2">
          Give rides and earn money
        </Text>
      </TouchableOpacity>
    </SafeAreaView>
  );
};

export default RoleSelection;
