import { useAuth } from "@/constants/AuthContext";
import { useTheme } from "@/hooks/use-theme";
import { authStyles } from "@/styles/auth.styles";
import { Feather } from "@expo/vector-icons";
import { router, useLocalSearchParams } from "expo-router";
import React, { useEffect, useMemo, useRef, useState } from "react";
import {
  Alert,
  KeyboardAvoidingView,
  Platform,
  ScrollView,
  Text,
  TextInput,
  TouchableOpacity,
  View,
} from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";
import apiClient from "../../services/api";

export default function OTPRegister() {
  const { phoneNumber } = useLocalSearchParams<{ phoneNumber: string }>();
  const [otp, setOtp] = useState("");
  const [focusedField, setFocusedField] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [timeLeft, setTimeLeft] = useState(120);
  const [canResend, setCanResend] = useState(false);
  const { signIn } = useAuth();
  const theme = useTheme();

  const scrollViewRef = useRef<ScrollView>(null);

  useEffect(() => {
    if (timeLeft <= 0) {
      setCanResend(true);
      return;
    }
    const timer = setInterval(() => {
      setTimeLeft((prev) => prev - 1);
    }, 1000);
    return () => clearInterval(timer);
  }, [timeLeft]);

  const handleBack = () => {
    router.back();
  };

  const handleVerifyOTP = async () => {
    if (!otp || otp.length < 4) {
      Alert.alert("خطا", "لطفا کد تایید را کامل وارد کنید");
      return;
    }

    setIsLoading(true);
    try {
      const response = await apiClient.post("/api/auth/verify_register/", {
        phone_number: phoneNumber,
        code: otp,
      });
      const { access } = response.data;
      await signIn(access);
    } catch (error: any) {
      Alert.alert(
        "خطا",
        error.response?.data?.message || "کد تایید اشتباه است",
      );
    } finally {
      setIsLoading(false);
    }
  };

  const handleResendCode = async () => {
    if (!phoneNumber) return;
    if (!canResend) {
      Alert.alert("صبر کنید", `لطفاً ${timeLeft} ثانیه دیگر تلاش کنید`);
      return;
    }

    setIsLoading(true);
    try {
      await apiClient.post("/api/auth/login/", { phone_number: phoneNumber });
      Alert.alert("کد مجدداً ارسال شد");
      setTimeLeft(120);
      setCanResend(false);
    } catch (error: any) {
      Alert.alert("خطا", "مشکل در ارسال مجدد کد");
    } finally {
      setIsLoading(false);
    }
  };

  const formatTime = (seconds: number) => {
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${mins}:${secs < 10 ? "0" : ""}${secs}`;
  };

  const handleFocus = () => {
    setTimeout(() => {
      scrollViewRef.current?.scrollTo({ y: 120, animated: true });
    }, 100);
  };

  const styles = useMemo(
    () => authStyles(theme, focusedField),
    [theme, focusedField],
  );

  return (
    <SafeAreaView style={styles.safeArea}>
      <KeyboardAvoidingView
        behavior={Platform.OS === "ios" ? "padding" : "height"}
        style={{ flex: 1 }}
        keyboardVerticalOffset={Platform.OS === "ios" ? 0 : 20}
      >
        <ScrollView
          ref={scrollViewRef}
          contentContainerStyle={styles.scrollContainer}
          showsVerticalScrollIndicator={false}
          keyboardShouldPersistTaps="handled"
        >
          <View style={{ marginBottom: 12 }}>
            <TouchableOpacity
              onPress={handleBack}
              style={{
                width: 32,
                height: 32,
                borderRadius: 8,
                backgroundColor: theme.backgroundElement,
                borderWidth: 0.5,
                borderColor: theme.border,
                alignItems: "center",
                justifyContent: "center",
              }}
            >
              <Feather
                name="arrow-left"
                size={16}
                color={theme.textSecondary}
              />
            </TouchableOpacity>
          </View>

          <View style={styles.phoneCard}>
            <View style={styles.headerRow}>
              <View style={styles.iconCircle}>
                <Feather name="key" size={18} color={theme.accent} />
              </View>
              <View style={styles.headerTextContainer}>
                <Text style={styles.headerTitle}>تایید کد</Text>
              </View>
            </View>

            <Text style={styles.subtitle}>
              کد تایید برای شماره {phoneNumber} ارسال شد
            </Text>

            <Text style={styles.fieldLabel}>کد تایید</Text>
            <View style={styles.inputContainer}>
              <Feather
                name="key"
                size={14}
                color={
                  focusedField === "otp" ? theme.accent : theme.textSecondary
                }
              />
              <TextInput
                style={styles.textInput}
                placeholder="کد ۶ رقمی"
                placeholderTextColor={theme.inputPlaceholder}
                value={otp}
                onChangeText={setOtp}
                onFocus={() => {
                  setFocusedField("otp");
                  handleFocus();
                }}
                onBlur={() => setFocusedField(null)}
                keyboardType="number-pad"
                maxLength={6}
                autoFocus
                textAlign="center"
              />
            </View>

            <TouchableOpacity
              disabled={isLoading}
              style={styles.continueButton}
              onPress={handleVerifyOTP}
            >
              {!isLoading && (
                <Feather name="arrow-left" size={14} color="#fff" />
              )}
              <Text style={styles.continueText}>
                {isLoading ? "در حال تایید..." : "تایید کد"}
              </Text>
            </TouchableOpacity>

            <TouchableOpacity
              disabled={isLoading || !canResend}
              style={[
                styles.secondaryButton,
                (!canResend || isLoading) && styles.secondaryButtonDisabled,
              ]}
              onPress={handleResendCode}
            >
              <Feather
                name="refresh-cw"
                size={14}
                color={
                  !canResend || isLoading ? theme.textSecondary : theme.accent
                }
              />
              <Text
                style={[
                  styles.secondaryButtonText,
                  (!canResend || isLoading) &&
                    styles.secondaryButtonTextDisabled,
                ]}
              >
                {!canResend
                  ? `ارسال مجدد کد (${formatTime(timeLeft)})`
                  : "ارسال مجدد کد"}
              </Text>
            </TouchableOpacity>
          </View>
        </ScrollView>
      </KeyboardAvoidingView>
    </SafeAreaView>
  );
}
