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

export default function ResetPassword() {
  const insets = useSafeAreaInsets();
  const { height: screenHeight } = Dimensions.get("window");

  const [password, setPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [isLoading, setIsLoading] = useState(false);
  const [showToast, setShowToast] = useState(false);
  const [errors, setErrors] = useState({});
  const [passwordStrength, setPasswordStrength] = useState(0);
  const [toastType, setToastType] = useState("error");
  const [toastMessage, setToastMessage] = useState("");

  const handleBack = () => {
    router.push("/verify-email");
  };

  const validatePasswords = () => {
    const newErrors = {};

    if (!password) {
      newErrors.password = "Şifre gerekli";
    } else if (password.length < 8) {
      newErrors.password = "Şifre en az 8 karakter olmalı";
    }

    if (!confirmPassword) {
      newErrors.confirmPassword = "Şifre tekrarı gerekli";
    } else if (password !== confirmPassword) {
      newErrors.confirmPassword = "Şifreler eşleşmiyor";
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleResetPassword = async () => {
    if (validatePasswords()) {
      setIsLoading(true);
      try {
        const email = await SecureStore.getItem("email");
        const code = await SecureStore.getItem("code");

        const response = await resetPassword({
          email: email,
          newPassword: password,
          code: code,
        });

        if (response.success) {
          setToastMessage("Şifreniz başarıyla güncellendi.");
          setToastType("success");
          setShowToast(true);
          await SecureStore.deleteItemAsync("email");
          await SecureStore.deleteItemAsync("code");
          setTimeout(() => {
            router.push("/login");
          }, 1500);
        } else {
          setToastMessage(
            response?.message || "Bir hata oluştu. Lütfen tekrar deneyin."
          );
          setToastType("error");
          setShowToast(true);
        }
      } catch (error) {
        console.error("Reset password error:", error);
        setToastMessage("Bir hata oluştu. Lütfen tekrar deneyin.");
        setToastType("error");
        setShowToast(true);
      } finally {
        setIsLoading(false);
      }
    }
  };

  // Calculate password strength
  const checkPasswordStrength = (pass) => {
    if (!pass) {
      setPasswordStrength(0);
      return;
    }

    let strength = 0;

    // Length check
    if (pass.length >= 8) strength += 1;

    // Contains uppercase letters
    if (/[A-Z]/.test(pass)) strength += 1;

    // Contains numbers
    if (/\d/.test(pass)) strength += 1;

    // Contains special characters
    if (/[^A-Za-z0-9]/.test(pass)) strength += 1;

    setPasswordStrength(Math.min(strength, 3));
  };

  return (
    <LinearGradient colors={["#E35367", "#B4001A", "#bd4050"]} style={styles.container}>
      <StatusBar style="light" />
      
      <Image
        source={require("@/assets/images/authentication/shield.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}>Yeni Şifre Oluştur</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}>
                Güvenliğin için güçlü bir şifre belirlemeyi öneririz. En az 8
                karakter, büyük harf, küçük harf ve sayı içermesine dikkat et.
              </Text>
            </View>

            <Input
              label="Yeni Şifreniz"
              placeholder="info: XaZka2sa3"
              value={password}
              onChangeText={(text) => {
                setPassword(text);
                if (errors.password) setErrors({ ...errors, password: "" });
                checkPasswordStrength(text);
              }}
              error={errors.password}
              isPassword={true}
              leftIcon={
                <Image
                  source={require("@/assets/images/icons/password.png")}
                  style={styles.inputIcon}
                />
              }
              style={styles.inputStyle}
            />

            <Input
              label="Yeni Şifre Tekrar"
              placeholder="info: XaZka2sa3"
              value={confirmPassword}
              onChangeText={(text) => {
                setConfirmPassword(text);
                if (errors.confirmPassword)
                  setErrors({ ...errors, confirmPassword: "" });
              }}
              error={errors.confirmPassword}
              isPassword={true}
              leftIcon={
                <Image
                  source={require("@/assets/images/icons/password.png")}
                  style={styles.inputIcon}
                />
              }
              style={styles.inputStyle}
            />

            <TouchableOpacity
              style={styles.loginButton}
              onPress={handleResetPassword}
              disabled={!password || !confirmPassword || isLoading}
              activeOpacity={0.8}
            >
              <LinearGradient
                colors={["#FF0025", "#FF0025", "#FF0025"]}
                style={styles.loginButtonGradient}
              >
                <Text style={styles.loginButtonText}>
                  {isLoading ? "Yenileniyor..." : "Yenile"}
                </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,
    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,
  },
  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: 16,
  },
  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",
  },
});
