import React, { useState } from "react";
import {
  View,
  TextInput,
  ActivityIndicator,
  KeyboardAvoidingView,
  Platform,
} from "react-native";
import { useSirouRouter } from "@sirou/react-native";
import { useLocalSearchParams, Stack } from "expo-router";
import { AppRoutes } from "@/lib/routes";
import { Text } from "@/components/ui/text";
import { Button } from "@/components/ui/button";
import { ScreenWrapper } from "@/components/ScreenWrapper";
import { StandardHeader } from "@/components/StandardHeader";
import { Phone } from "@/lib/icons";
import { api } from "@/lib/api";
import { toast } from "@/lib/toast-store";
import { useColorScheme } from "nativewind";
import { getPlaceholderColor } from "@/lib/colors";

export default function ForgotPinScreen() {
  const nav = useSirouRouter<AppRoutes>();
  const params = useLocalSearchParams<{ phone?: string }>();
  const { colorScheme } = useColorScheme();
  const isDark = colorScheme === "dark";

  const [phone, setPhone] = useState(params.phone || "");
  const [loading, setLoading] = useState(false);

  const handleSendOtp = async () => {
    if (!phone || phone.length < 9) {
      toast.error("Required", "Please enter your phone number");
      return;
    }

    setLoading(true);
    const fullPhone = `+251${phone}`;
    try {
      const response = await api.auth.forgetPin({ body: { phone: fullPhone } });
      toast.success("OTP Sent", response.message || "Verification code sent to your phone");
      nav.go("forgot-pin-verify", { phone: fullPhone, verificationId: response.verificationId });
    } catch (err: any) {
      toast.error("Failed", err.message || "Could not send OTP");
    } finally {
      setLoading(false);
    }
  };

  return (
    <ScreenWrapper className="bg-background">
      <Stack.Screen options={{ headerShown: false }} />
      <StandardHeader title="Reset PIN" showBack />

      <KeyboardAvoidingView
        behavior={Platform.OS === "ios" ? "padding" : "height"}
        className="flex-1"
      >
        <View className="flex-1 px-6 pt-10">
          <View className="items-center mb-10">
            <Text variant="h4" className="font-sans-bold text-foreground">
              Forgot your PIN?
            </Text>
            <Text variant="muted" className="mt-2 text-center text-sm">
              Enter your phone number to receive a verification code
            </Text>
          </View>

          <View>
            <Text variant="small" className="font-sans-semibold mb-2 ml-1">
              Phone Number
            </Text>
            <View className="flex-row items-center rounded-xl px-4 border border-border h-12">
              <Phone size={18} color={isDark ? "#94a3b8" : "#64748b"} />
              <Text className="ml-2 text-foreground font-sans-bold">+251</Text>
              <TextInput
                className="flex-1 ml-2 text-foreground py-0"
                placeholder="912345678"
                placeholderTextColor={getPlaceholderColor(isDark)}
                value={phone}
                onChangeText={setPhone}
                keyboardType="phone-pad"
                maxLength={9}
                style={{ textAlignVertical: "center" }}
              />
            </View>
          </View>

          <Button
            className="h-12 bg-primary rounded-[10px] mt-6"
            onPress={handleSendOtp}
            disabled={loading || phone.length < 9}
          >
            {loading ? (
              <ActivityIndicator color="white" />
            ) : (
              <Text className="text-white font-sans-bold text-base">
                Send Verification Code
              </Text>
            )}
          </Button>
        </View>
      </KeyboardAvoidingView>
    </ScreenWrapper>
  );
}
