import React, { useState } from "react";
import { useRouter } from "next/router";
import { useTranslation } from "react-i18next";
import { useAuth } from "@/context/helpers/auth/AuthContext";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
import { Button } from "@/components/ui/button";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Mail, Loader2, ArrowLeft, CheckCircle2 } from "lucide-react";
import Link from "next/link";
import { Alert, AlertDescription } from "@/components/ui/alert";

export default function ForgotPasswordPage() {
  const { t } = useTranslation("auth");
  const router = useRouter();
  const { resetPassword, isLoading, errorMessage } = useAuth();
  const [isSuccess, setIsSuccess] = useState(false);

  // Zod validation schema
  const formSchema = z.object({
    email: z
      .string()
      .email({ message: t("emailInvalid", "Email is invalid") })
      .min(1, { message: t("emailRequired", "Email is required") }),
  });

  // Initialize form with react-hook-form
  const form = useForm({
    resolver: zodResolver(formSchema),
    defaultValues: {
      email: "",
    },
  });

  // Handle form submission
  const onSubmit = async (data) => {
    const result = await resetPassword(data.email);

    // Check if the result is successful (resetPassword returns a promise)
    if (result !== false) {
      setIsSuccess(true);
    }
  };

  // Success state
  if (isSuccess) {
    return (
      <main className="min-h-screen bg-gradient-to-br from-gray-50 to-gray-100">
        <div className="container px-4 py-8 mx-auto">
          <div className="flex min-h-[calc(100vh-4rem)] items-center justify-center">
            <div className="w-full max-w-md">
              <div className="overflow-hidden bg-white shadow-xl rounded-2xl">
                <div className="p-8 text-center">
                  <div className="flex justify-center mb-6">
                    <div className="flex items-center justify-center w-20 h-20 bg-green-100 rounded-full">
                      <CheckCircle2 className="w-12 h-12 text-green-600" />
                    </div>
                  </div>

                  <h1 className="mb-3 text-2xl font-bold text-gray-900">
                    {t("checkYourEmail", "Check Your Email")}
                  </h1>

                  <p className="mb-6 text-gray-600">
                    {t(
                      "resetLinkSent",
                      "We've sent a password reset link to your email address. Please check your inbox and follow the instructions."
                    )}
                  </p>

                  <div className="space-y-3">
                    <Button
                      onClick={() => router.push("/account/login")}
                      className="w-full py-6 font-semibold text-white rounded-lg bg-mainColor hover:bg-mainColor/90"
                    >
                      {t("backToLogin", "Back to Login")}
                    </Button>

                    <Button
                      onClick={() => setIsSuccess(false)}
                      variant="outline"
                      className="w-full py-6"
                    >
                      {t("resendEmail", "Resend Email")}
                    </Button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </main>
    );
  }

  return (
    <main className="min-h-screen bg-gradient-to-br from-gray-50 to-gray-100">
      <div className="container px-4 py-8 mx-auto">
        <div className="flex min-h-[calc(100vh-4rem)] items-center justify-center">
          <div className="w-full max-w-md">
            {/* Card */}
            <div className="overflow-hidden bg-white shadow-xl rounded-2xl">
              {/* Header */}
              <div className="p-8 text-white bg-gradient-to-r from-mainColor to-mainColor/90">
                <div className="flex justify-center mb-4">
                  <div className="flex items-center justify-center w-16 h-16 bg-white rounded-full">
                    <Mail className="w-8 h-8 text-mainColor" />
                  </div>
                </div>
                <h1 className="mb-2 text-2xl font-bold text-center">
                  {t("forgotPassword", "Forgot Password?")}
                </h1>
                <p className="text-sm text-center text-white/90">
                  {t(
                    "forgotPasswordSubtitle",
                    "Enter your email and we'll send you a reset link"
                  )}
                </p>
              </div>

              {/* Form */}
              <div className="p-8">
                {/* Error Message from API */}
                {errorMessage && (
                  <Alert variant="destructive" className="mb-6">
                    <AlertDescription>{errorMessage}</AlertDescription>
                  </Alert>
                )}

                <Form {...form}>
                  <form
                    onSubmit={form.handleSubmit(onSubmit)}
                    className="space-y-6"
                  >
                    {/* Email Field */}
                    <FormField
                      control={form.control}
                      name="email"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>
                            {t("email", "Email Address")}
                          </FormLabel>
                          <FormControl>
                            <div className="relative">
                              <Mail className="absolute w-5 h-5 text-gray-400 -translate-y-1/2 left-3 top-1/2" />
                              <Input
                                {...field}
                                type="email"
                                placeholder="you@example.com"
                                className="pl-10"
                                autoComplete="email"
                              />
                            </div>
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    {/* Submit Button */}
                    <Button
                      type="submit"
                      disabled={isLoading}
                      className="w-full py-6 font-semibold text-white transition-all duration-200 rounded-lg cursor-pointer bg-mainColor hover:bg-mainColor/90"
                    >
                      {isLoading ? (
                        <>
                          <Loader2 className="w-5 h-5 mr-2 animate-spin" />
                          {t("sendingResetLink", "Sending reset link...")}
                        </>
                      ) : (
                        t("sendResetLink", "Send Reset Link")
                      )}
                    </Button>
                  </form>
                </Form>

                {/* Back to Login Link */}
                <div className="mt-6">
                  <Link
                    href="/account/login"
                    className="flex items-center justify-center gap-2 text-sm text-gray-600 transition-colors hover:text-mainColor"
                  >
                    <ArrowLeft className="w-4 h-4" />
                    {t("backToLogin", "Back to Login")}
                  </Link>
                </div>
              </div>
            </div>

            {/* Help text */}
            <p className="mt-8 text-sm text-center text-gray-500">
              {t(
                "resetPasswordHelp",
                "If you don't receive an email within a few minutes, please check your spam folder or try again."
              )}
            </p>
          </div>
        </div>
      </div>
    </main>
  );
}
