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 React, { useRef, useState } from "react";
import {
  Image,
  KeyboardAvoidingView,
  Platform,
  SafeAreaView,
  ScrollView,
  StyleSheet,
  Text,
  TextInput,
  TouchableOpacity,
  View,
  Dimensions,
} from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { verifyEmail } from "../../services/user";

export default function VerifyEmail() {
  const insets = useSafeAreaInsets();
  const { height: screenHeight } = Dimensions.get("window");
  
  const [code, setCode] = useState(["", "", "", "", "", ""]);
  const [timer, setTimer] = useState(107); // 1:47 in seconds
  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) {
      setIsLoading(true);

      try {
        const email = await SecureStore.getItemAsync("email");

        const response = await verifyEmail({
          code: code.join(""),
          email: email,
        });

        if (response?.success) {
          setToast({
            visible: true,
            type: "success",
            title: "Doğrulama Başarılı",
            message: "E-mailiniz başarıyla doğrulandı. Giriş yapabilirsiniz."
          });
          setTimeout(() => {
            router.replace("/(auth)/login");
          }, 1500);
        } else {
          setToast({
            visible: true,
            type: "error",
            title: "Hata",
            message: response?.message || "Bir hata oluştu. Lütfen tekrar deneyin."
          });
        }
      } catch (error) {
        console.error("Verify Error:", error);
        setToast({
          visible: true,
          type: "error",
          title: "Hata",
          message: error?.message || "Bir hata oluştu. Lütfen tekrar deneyin."
        });
      } finally {
        setIsLoading(false);
      }
    } else {
      setToast({
        visible: true,
        type: "error",
        title: "Hata",
        message: "Kod 6 haneli olmalıdır."
      });
    }
  };

  const handleCodeChange = (text, index) => {
    if (/^\d*$/.test(text)) {
      const newCode = [...code];
      newCode[index] = text;
      setCode(newCode);

      // Auto-advance to next input
      if (text.length === 1 && index < code.length - 1) {
        inputRefs.current[index + 1].focus();
      }
    }
  };

  const handleKeyPress = (e, index) => {
    // Handle backspace to go to previous input
    if (e.nativeEvent.key === "Backspace" && !code[index] && index > 0) {
      inputRefs.current[index - 1].focus();
    }
  };

  const handleBack = () => {
    router.push("/(auth)/register");
  };

  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={handleBack}>
          <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}>E-posta Adresine{"\n"}Kod 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}>
                Lütfen e-posta adresine gelen 6 haneli doğrulama kodunu aşağıya
                gir. Kod birkaç dakika içinde ulaşmazsa spam klasörünü kontrol
                etmeyi unutma.
              </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 ? "Kod Gönderiliyor..." : "Kod Gönder"}
                </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(prev => ({ ...prev, visible: false }))}
      />
    </LinearGradient>
  );
}

const styles = StyleSheet.create({
  logoContainer: {
    position: "absolute",
    width: "100%",
    alignItems: "center",
    bottom: 0,
    zIndex: 10,
  },
  formBackgroundImage: {
    width: 80,
    height: 80,
  },
  container: {
    ...FLEX.fill,
  },
  safeArea: {
    width: "100%",
    zIndex: 2,
  },
  backButton: {
    padding: 16,
    position: "absolute",
    zIndex: 10,
    top: 40,
  },
  topSection: {
    flex: 0.4,
    width: "100%",
    zIndex: 1,
  },
  backgroundImage: {
    position: "absolute",
    top: 0,
    left: 0,
    right: 0,
    width: "100%",
    height: "60%",
    zIndex: 0,
  },
  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",
    borderTopLeftRadius: 30,
    borderTopRightRadius: 30,
    borderBottomLeftRadius: 30,
    borderBottomRightRadius: 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",
  },
});
