"use client";

import { useState } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { IoArrowBack } from "react-icons/io5";
import toast from "react-hot-toast";
import { useTranslations } from "next-intl";

interface ForgotPasswordFormProps {
  onBackToLogin: () => void;
  onEmailSent: (email: string) => void;
}

export default function ForgotPasswordForm({
  onBackToLogin,
  onEmailSent,
}: ForgotPasswordFormProps) {
  const t = useTranslations("auth");
  const [isLoading, setIsLoading] = useState(false);

  const forgotPasswordSchema = z.object({
    email: z.string().email(t("invalid-email") || "Please enter a valid email address"),
  });

  type ForgotPasswordFormData = z.infer<typeof forgotPasswordSchema>;

  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<ForgotPasswordFormData>({
    resolver: zodResolver(forgotPasswordSchema),
  });

  const onSubmit = async (data: ForgotPasswordFormData) => {
    setIsLoading(true);

    try {
      const response = await fetch('/api/customer/forgotpassword', {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ email: data.email }),
      });

      const result = await response.json();

      if (!response.ok) {
        toast.error(result.message || t("unexpected-error") || "Failed to send reset code");
        return;
      }

      toast.success(result.message || t("otp-sent") || "Reset code sent successfully");
      onEmailSent(result.email || data.email);
    } catch (error) {
      console.error(error);
      toast.error(t("unexpected-error") || "An error occurred. Please try again.");
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <Card className="w-full max-w-md mx-auto">
      <CardHeader className="text-center">
        <CardTitle className="text-2xl font-bold">
          {t("password-recovery") || "نسيت كلمة المرور"}
        </CardTitle>
        <p className="text-muted-foreground">
          {t("follow-steps") || "اتبع الخطوات لإعادة تعيين كلمة المرور"}
        </p>
      </CardHeader>

      <CardContent>
        <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
          {/* Email Input */}
          <div className="space-y-1">
            <Label htmlFor="forgot-email" className="block text-sm font-medium text-start">
              {t("email") || "البريد الإلكتروني"}
            </Label>
            <Input
              id="forgot-email"
              {...register("email")}
              type="email"
              dir="ltr"
              placeholder={t("email-placeholder") || "أدخل بريدك الإلكتروني"}
              className={errors.email ? "border-red-500" : ""}
              disabled={isLoading}
            />
            {errors.email && (
              <p className="text-red-500 text-sm mt-1 text-start">
                {errors.email.message}
              </p>
            )}
          </div>

          {/* Submit Button */}
          <Button type="submit" className="w-full" disabled={isLoading}>
            {isLoading
              ? (t("sending") || "جاري الإرسال...")
              : (t("send-reset-link") || "إرسال رابط إعادة التعيين")}
          </Button>

          {/* Back to Login Link */}
          <div className="text-center">
            <button
              type="button"
              onClick={onBackToLogin}
              className="cursor-pointer text-primary hover:underline text-sm flex items-center justify-center gap-2 mx-auto"
              disabled={isLoading}
            >
              <IoArrowBack className="text-sm" />
              {t("back-to-login") || "العودة لتسجيل الدخول"}
            </button>
          </div>
        </form>
      </CardContent>
    </Card>
  );
}
