"use client";

import { useState } from "react";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { forgotPassword, clearError } from "@/store/slices/authSlice";
import { AuthField } from "./AuthField";
import { useTranslation } from "@/i18n";
import { ArrowLeft, CheckCircle } from "lucide-react";
import Link from "next/link";

const schema = z.object({
  email: z.string().email("Enter a valid email"),
});
type FormValues = z.infer<typeof schema>;

export function ForgotPasswordPage() {
  const dispatch = useAppDispatch();
  const { isLoading, error } = useAppSelector((s) => s.auth);
  const { t } = useTranslation();
  const [success, setSuccess] = useState(false);

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

  const onSubmit = async (data: FormValues) => {
    dispatch(clearError());
    const res = await dispatch(forgotPassword(data.email));
    if (forgotPassword.fulfilled.match(res)) {
      setSuccess(true);
    }
  };

  return (
    <div
      className="rounded-2xl p-8"
      style={{
        background: "var(--auth-card-bg)",
        backdropFilter: "blur(20px)",
        WebkitBackdropFilter: "blur(20px)",
        border: "1px solid var(--border)",
        boxShadow: "var(--auth-card-shadow)",
      }}
    >
      <Link
        href="/auth/login"
        className="inline-flex items-center gap-2 text-xs font-medium mb-6 transition-opacity hover:opacity-80"
        style={{ color: "var(--text-muted)" }}
      >
        <ArrowLeft size={14} /> {t("auth_backToLogin")}
      </Link>

      {success ? (
        <div className="flex flex-col items-center gap-5 py-4">
          <div
            className="w-16 h-16 rounded-full flex items-center justify-center"
            style={{ background: "rgba(34,197,94,0.12)" }}
          >
            <CheckCircle size={32} className="text-green-400" />
          </div>
          <div className="text-center">
            <h2 className="text-xl font-black mb-2" style={{ color: "var(--text-primary)" }}>{t("auth_forgotSuccess")}</h2>
            <p className="text-sm" style={{ color: "var(--text-muted)" }}>
              {t("auth_checkInbox")}
            </p>
          </div>
          <Link
            href="/auth/login"
            className="px-6 py-2.5 rounded-xl text-sm font-bold text-[#ffffff] transition-all duration-150 active:scale-[0.98]"
            style={{ background: "var(--accent)" }}
          >
            {t("auth_backToLogin")}
          </Link>
        </div>
      ) : (
        <>
          <h1 className="text-2xl font-black tracking-tight mb-1" style={{ color: "var(--text-primary)" }}>
            {t("auth_forgotTitle")}
          </h1>
          <p className="text-sm mb-7" style={{ color: "var(--text-muted)" }}>
            {t("auth_forgotSubtext")}
          </p>

          <form onSubmit={handleSubmit(onSubmit)} className="flex flex-col gap-4">
            <AuthField
              label={t("auth_emailLabel")}
              type="email"
              placeholder="you@example.com"
              error={errors.email?.message}
              autoComplete="email"
              {...register("email")}
            />

            {error && (
              <p className="text-xs px-3 py-2 rounded-lg" style={{ background: "rgba(239,68,68,0.1)", color: "#ef4444" }}>
                {error}
              </p>
            )}

            <button
              type="submit"
              disabled={isLoading}
              className="w-full py-3 rounded-xl text-sm font-bold tracking-wide text-[#ffffff] transition-all duration-150 active:scale-[0.98] disabled:opacity-60 mt-1"
              style={{ background: "var(--accent)" }}
            >
              {isLoading ? t("auth_sending") : t("auth_sendResetLink")}
            </button>
          </form>
        </>
      )}
    </div>
  );
}
