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

export default function ForgotPassword() {
  const insets = useSafeAreaInsets();
  const { height: screenHeight } = Dimensions.get("window");
  
  const [email, setEmail] = useState("");
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState("");
  const [showToast, setShowToast] = useState(false);
  const [toastMessage, setToastMessage] = useState("");
  const [toastType, setToastType] = useState("error");

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

  const validateEmail = (email) => {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
  };

  const handleSendCode = async () => {
    if (!email) {
      setError("E-posta adresi gerekli");
      return;
    }

    if (!validateEmail(email)) {
      setError("Geçerli bir e-posta adresi girin");
      return;
    }

    setError("");
    setIsLoading(true);

    try {
      const response = await forgotPassword({ email });

      if (response?.success) {
        setToastMessage(
          response?.message || "Doğrulama kodu e-posta adresinize gönderildi."
        );
        setToastType("success");
        setShowToast(true);

        await SecureStore.setItem("email", email);
        setTimeout(() => {
          router.push("/(auth)/verify-forgot");
        }, 1500);
      } else {
        setToastMessage(response?.message || "Doğrulama kodu gönderilemedi.");
        setToastType("error");
        setShowToast(true);
      }
    } catch (error) {
      setToastMessage(
        error?.message || "Bir hata oluştu. Lütfen tekrar deneyin."
      );
      setToastType("error");
      setShowToast(true);
    } finally {
      setIsLoading(false);
    }
  };

  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={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}>Şifrenizi mi unuttunuz?</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.subtitleContainer}>
              <Text style={styles.subtitle}>
                Endişelenme, birkaç adımda yeni bir şifre oluşturabilirsin.
                Aşağıya hesabına ait e-posta adresini yaz, sana doğrulama kodu
                gönderelim.
              </Text>
            </View>

            <Input
              label="E-Mail Adresiniz"
              placeholder="info@example.com"
              value={email}
              onChangeText={(text) => {
                setEmail(text);
                setError("");
              }}
              error={error}
              keyboardType="email-address"
              autoCapitalize="none"
              leftIcon={
                <Image
                  source={require("@/assets/images/icons/email.png")}
                  style={styles.inputIcon}
                />
              }
              style={styles.inputStyle}
            />

            <TouchableOpacity
              style={styles.loginButton}
              onPress={handleSendCode}
              disabled={!email || 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={showToast}
        message={toastMessage}
        type={toastType}
        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",
  },
  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,
  },
  subtitleContainer: {
    alignItems: "center",
    marginBottom: 24,
  },
  subtitle: {
    ...paragraph["M/Regular"],
    color: COLOR_SCALES.gray[50],
    textAlign: "center",
  },
  inputIcon: {
    width: 20,
    height: 20,
    opacity: 0.5,
  },
  inputStyle: {
    marginBottom: 24,
  },
  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",
  },
});
