import { Toast } from "@/components/common";
import { COLOR_SCALES } from "@/theme/colors";
import { FLEX } from "@/theme/mixins";
import { paragraph, title } from "@/theme/typography";
import { Ionicons } from "@expo/vector-icons";
import { LinearGradient } from "expo-linear-gradient";
import { router } from "expo-router";
import * as SecureStore from "expo-secure-store";
import { StatusBar } from "expo-status-bar";
import { useRef, useState } from "react";
import {
  Image,
  KeyboardAvoidingView,
  Platform,
  ScrollView,
  StyleSheet,
  Text,
  TextInput,
  TouchableOpacity,
  View,
} from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { verifyForgotCode } from "../../services/user";

export default function VerifyForgot() {
  const insets = useSafeAreaInsets();
  const [code, setCode] = useState(["", "", "", "", "", ""]);
  const [isLoading, setIsLoading] = useState(false);
  const [toast, setToast] = useState({ visible: false, type: "error", message: "", title: "" });
  const inputRefs = useRef([]);

  const handleVerify = async () => {
    if (code.join("").length !== 6) {
      setToast({ visible: true, type: "error", title: "Hata", message: "Kod 6 haneli olmalıdır." });
      return;
    }
    setIsLoading(true);
    try {
      const email = await SecureStore.getItemAsync("email");
      const response = await verifyForgotCode({ code: code.join(""), email });

      if (response?.success) {
        await SecureStore.setItemAsync("code", code.join(""));
        setToast({ visible: true, type: "success", title: "Doğrulama Başarılı", message: "Yeni şifrenizi belirleyebilirsiniz." });
        setTimeout(() => router.replace("/(auth)/reset-password"), 1500);
      } else {
        setToast({ visible: true, type: "error", title: "Hata", message: response?.message || "Geçersiz kod." });
      }
    } catch (error) {
      setToast({ visible: true, type: "error", title: "Hata", message: error?.message || "Bir hata oluştu." });
    } finally {
      setIsLoading(false);
    }
  };

  const handleCodeChange = (text, index) => {
    if (/^\d*$/.test(text)) {
      const newCode = [...code];
      newCode[index] = text;
      setCode(newCode);
      if (text.length === 1 && index < 5) inputRefs.current[index + 1].focus();
    }
  };

  const handleKeyPress = (e, index) => {
    if (e.nativeEvent.key === "Backspace" && !code[index] && index > 0) {
      inputRefs.current[index - 1].focus();
    }
  };

  return (
    <LinearGradient colors={["#E35367", "#B4001A", "#bd4050"]} style={styles.container}>
      <StatusBar style="light" />
      <Image source={require("@/assets/images/authentication/paper-plane.png")} style={styles.backgroundImage} resizeMode="cover" />

      <SafeAreaView style={styles.safeArea}>
        <TouchableOpacity style={styles.backButton} onPress={() => router.push("/(auth)/forgot-password")}>
          <Ionicons name="arrow-back" size={24} color={COLOR_SCALES.white.white} />
        </TouchableOpacity>
      </SafeAreaView>

      <View style={styles.topSection}>
        <SafeAreaView style={styles.topContent}>
          <View style={styles.textContainer}>
            <Text style={styles.title}>Şifre Sıfırlama{"\n"}Kodu Gönderildi</Text>
          </View>
        </SafeAreaView>
      </View>

      <View style={styles.formSection}>
        <KeyboardAvoidingView behavior="padding" style={styles.keyboardContainer}>
          <ScrollView style={styles.scrollContainer} contentContainerStyle={styles.formContainer} showsVerticalScrollIndicator={false} keyboardShouldPersistTaps="handled" bounces={false}>
            <View style={styles.helperTextContainer}>
              <Text style={styles.helperText}>
                Şifre sıfırlama için e-posta adresine gelen 6 haneli kodu gir.
              </Text>
            </View>

            <View style={styles.codeContainer}>
              {code.map((digit, index) => (
                <TextInput
                  key={index}
                  ref={(ref) => (inputRefs.current[index] = ref)}
                  style={[styles.codeInput, digit ? styles.codeInputFilled : styles.codeInputEmpty]}
                  value={digit}
                  onChangeText={(text) => handleCodeChange(text, index)}
                  onKeyPress={(e) => handleKeyPress(e, index)}
                  keyboardType="number-pad"
                  maxLength={1}
                  selectTextOnFocus
                />
              ))}
            </View>

            <TouchableOpacity style={styles.loginButton} onPress={handleVerify} disabled={isLoading} activeOpacity={0.8}>
              <LinearGradient colors={["#FF0025", "#FF0025", "#FF0025"]} style={styles.loginButtonGradient}>
                <Text style={styles.loginButtonText}>{isLoading ? "Doğrulanıyor..." : "Doğrula"}</Text>
              </LinearGradient>
            </TouchableOpacity>
          </ScrollView>
        </KeyboardAvoidingView>
      </View>

      <View style={[styles.logoContainer, { paddingBottom: Platform.select({ ios: Math.max(insets.bottom + 50, 60), android: Math.max(insets.bottom + 40, 50), default: 50 }) }]}>
        <Image source={require("@/assets/images/icons/small-logo.png")} style={styles.formBackgroundImage} />
      </View>

      <Toast visible={toast.visible} type={toast.type} title={toast.title} message={toast.message} onHide={() => setToast(p => ({ ...p, visible: false }))} />
    </LinearGradient>
  );
}

const styles = StyleSheet.create({
  container: { ...FLEX.fill },
  safeArea: { width: "100%", zIndex: 2 },
  backButton: { padding: 16, position: "absolute", zIndex: 10, top: 40 },
  backgroundImage: { position: "absolute", top: 0, left: 0, right: 0, width: "100%", height: "60%", zIndex: 0 },
  topSection: { flex: 0.4, width: "100%", zIndex: 1 },
  topContent: { flex: 1, alignItems: "center", justifyContent: "center", paddingTop: 20, paddingBottom: 20, zIndex: 1 },
  textContainer: { alignItems: "center", justifyContent: "center", marginTop: 40 },
  title: { ...title["L/Bold"], color: COLOR_SCALES.white.white, textAlign: "center", paddingHorizontal: 20, marginTop: 70, textShadowColor: "rgba(0,0,0,0.5)", textShadowOffset: { width: 1, height: 1 }, textShadowRadius: 2 },
  keyboardContainer: { flex: 1 },
  formSection: { flex: 1, width: "100%", paddingHorizontal: 20, marginTop: 20, paddingTop: 34, paddingBottom: 30, backgroundColor: "#fff", borderRadius: 30, marginBottom: Platform.select({ ios: 120, android: 110, default: 110 }) },
  scrollContainer: { flex: 1 },
  formContainer: { paddingHorizontal: 24, paddingBottom: 40 },
  helperTextContainer: { alignItems: "center", marginBottom: 24 },
  helperText: { ...paragraph["S/Regular"], color: COLOR_SCALES.gray[70], textAlign: "center" },
  codeContainer: { flexDirection: "row", justifyContent: "center", marginBottom: 24, gap: 8 },
  codeInput: { width: 48, height: 56, borderRadius: 8, fontSize: 24, fontWeight: "bold", textAlign: "center" },
  codeInputEmpty: { backgroundColor: "#fff", borderColor: COLOR_SCALES.gray[30], borderWidth: 1, color: COLOR_SCALES.gray[90] },
  codeInputFilled: { backgroundColor: "#fff", borderColor: "#DB0020", borderWidth: 2, color: "#DB0020" },
  loginButton: { alignSelf: "center", marginTop: 40, marginBottom: 20, borderRadius: 32, overflow: "hidden", width: "100%", borderBottomWidth: 3, borderTopWidth: 1, borderLeftWidth: 3, borderRightWidth: 3, borderColor: "#52000C" },
  loginButtonGradient: { paddingVertical: 15, paddingHorizontal: 40, alignItems: "center", justifyContent: "center" },
  loginButtonText: { ...paragraph["M/Bold"], color: "#fff", textAlign: "center" },
  logoContainer: { position: "absolute", width: "100%", alignItems: "center", bottom: 0, zIndex: 10 },
  formBackgroundImage: { width: 80, height: 80 },
});
