import AuthLayout from "@/components/auth/auth-layout";
import InputGroup from "@/components/auth/InputGroup";
import Button from "@/components/ui/Button";
import { useQueryMutation } from "@/hooks/mutate/useQueryMutation";
import { useColor } from "@/hooks/useColor";
import { showToast } from "@/utils/toast";
import { router } from "expo-router";
import { Key } from "phosphor-react-native";
import { useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import { Text, View } from "react-native";
import BackButtonTitle from "@/components/ui/BackButtonTitle";

type ForgotPasswordData = {
  type: string;
  email: string;
};

const isValidEmail = (value: string) => {
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
};

const isValidPhone = (value: string) => {
  return /^\+?\d{7,15}$/.test(value);
};

export default function ForgotPassword() {
  const [formData, setFormData] = useState({
    type: "email",
    email: "",
  });
  const { primary } = useColor();

  const {
    control,
    formState: { errors: formErrors },
    handleSubmit,
  } = useForm<ForgotPasswordData>({
    defaultValues: {
      type: "email",
    },
  });

  useEffect(() => {
    if (isValidEmail(formData.email)) {
      setFormData((prev) => ({ ...prev, type: "email" }));
    } else if (isValidPhone(formData.email)) {
      setFormData((prev) => ({ ...prev, type: "phone" }));
    }
  }, [formData.email]);

  const {
    mutate,
    isLoading,
    backendErrors: errors,
  } = useQueryMutation({
    isPublic: true,
    url: "/send-otp",
  });

  const onSubmit = handleSubmit((data) => {
    mutate(
      { ...data, type: "email" },
      {
        onSuccess: (response) => {
          showToast({
            type: "success",
            text: "OTP sent successfully",
          });
          router.push(`/(auth)/verify-otp-pass?email=${data.email}`);
        },
        onError: (err) => {
          console.log(err);
        },
      },
    );
  });

  return (
    <AuthLayout>
      <View className="pb-10">
        <View className="py-2">
          <BackButtonTitle title="Forgot Password" />
        </View>

        <View className="mt-8 mb-6 p-6 rounded-3xl" style={{ backgroundColor: primary[5] }}>
          <View
            className="size-14 rounded-2xl justify-center items-center shadow-sm"
            style={{ backgroundColor: "white" }}
          >
            <Key size={32} color={primary.base} weight="duotone" />
          </View>
          <Text className="text-3xl font-manrope-extrabold text-slate-900 pt-5">
            Reset Password
          </Text>
          <Text className="text-slate-500 w-[95%] pt-2 text-lg font-manrope-medium leading-6">
            Enter your email address and we&apos;ll send you an OTP to reset your password.
          </Text>
        </View>

        <View className="py-2 gap-y-6">
          <InputGroup
            control={control}
            label="Email Address"
            name="email"
            error={formErrors.email}
            backendError={errors?.email}
            keyboardType="email-address"
          />
          
          <Button
            onPress={onSubmit}
            isLoading={isLoading}
            text="Send OTP"
            className="mt-2"
          />
          
          <Text 
            onPress={() => router.back()}
            className="text-center font-manrope-bold text-base mt-2"
            style={{ color: primary.base }}
          >
            Back to Sign In
          </Text>
        </View>
      </View>
    </AuthLayout>
  );
}
