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

export default function VerifyPhone() {
  const insets = useSafeAreaInsets();
  const { height: screenHeight } = Dimensions.get("window");
  
  const [code, setCode] = useState("");
  const [isLoading, setIsLoading] = useState(false);
  const [showToast, setShowToast] = useState(false);
  const [toastMessage, setToastMessage] = useState("");
  const [toastType, setToastType] = useState("error");
 
  const handleVerify = async () => {
    if (code.length === 6) {
      setIsLoading(true);
      try {
        const email = await SecureStore.getItem("email");

        const response = await verifyAccount({
          code: code,
          email: email,
        });

        if (response.success) {
          setToastMessage("Hesap doğrulama başarılı");
          setToastType("success");
          setShowToast(true);
          await SecureStore.deleteItemAsync("email");
          setTimeout(() => {
            router.push("/login");
          }, 1500);
        } else {
          setToastMessage("Hesap doğrulama başarısız");
          setToastType("error");
          setShowToast(true);
        }
      } catch (error) {
        console.error("Verification error:", error);
        setToastMessage("Hesap doğrulama başarısız");
        setToastType("error");
        setShowToast(true);
        // Handle error - maybe show error toast
      } finally {
        setIsLoading(false);
      }
    }
  };

  const handleLogin = () => {
    router.push("/login");
  };

  return (
    <LinearGradient colors={["#E35367", "#B4001A", "#bd4050"]} style={styles.container}>
      <StatusBar style="light" />
      
      <Image
        source={require("@/assets/images/authentication/mail-stack.png")}
        style={styles.backgroundImage}
        resizeMode="cover"
      />
      
      <SafeAreaView style={styles.safeArea}>
        <TouchableOpacity
          style={styles.backButton}
          onPress={() => router.push("/register")}
        >
          <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}>Hesap Doğrulama</Text>
            <Text style={styles.subtitle}>
              Hesap Doğrulama İçin Gönderilen Kodu Girin
            </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}>
                Mail Adresinize gönderdiğimiz doğrulama kodunu aşağıya girin.
                Kod birkaç dakika içinde ulaşmazsa spam klasörünü kontrol
                etmeyi unutma.
              </Text>
            </View>

            <View style={styles.otpContainer}>
              <OTPInput value={code} onChange={setCode} length={6} />
            </View>

            <View style={styles.loginHelperContainer}>
              <Text style={styles.loginHelperText}>
                Hesabınıza giriş yapmak mı istiyorsunuz?
              </Text>
              <TouchableOpacity onPress={handleLogin}>
                <Text style={styles.loginLink}>Giriş Yap</Text>
              </TouchableOpacity>
            </View>

            <TouchableOpacity
              style={styles.loginButton}
              onPress={handleVerify}
              disabled={code.length !== 6 || 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={showToast}
        type={toastType}
        message={toastMessage}
        onHide={() => setShowToast(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,
    marginBottom: 8,
    textAlign: "center",
    paddingHorizontal: 20,
    marginTop: 100,
    textShadowColor: "rgba(0, 0, 0, 0.5)",
    textShadowOffset: { width: 1, height: 1 },
    textShadowRadius: 2,
  },
  subtitle: {
    ...paragraph["M/Regular"],
    color: COLOR_SCALES.white.white,
    textAlign: "center",
    paddingHorizontal: 20,
    marginBottom: 24,
  },
  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",
  },
  otpContainer: {
    width: "100%",
    marginBottom: 24,
  },
  loginHelperContainer: {
    flexDirection: "column",
    alignItems: "center",
    marginBottom: 20,
  },
  loginHelperText: {
    ...paragraph["S/Regular"],
    color: COLOR_SCALES.gray[50],
  },
  loginLink: {
    ...paragraph["S/Bold"],
    color: "#FF0025",
    textDecorationLine: "underline",
    marginTop: 4,
  },
  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",
  },
});
