"use client";

import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { Field, FieldLabel } from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import { AlertMessage } from "@/components/ui/AlertMessage";
import { FormEvent, useState, useEffect } from "react";
import { Mail, Loader2 } from "lucide-react";
import { validateEmail, clearFieldError } from "@/utils/form-validation";
import { PRIMARY_COLOR, PRIMARY_COLOR_HOVER } from "@/lib/common";

export function ForgotForm({
  className,
  ...props
}: React.ComponentProps<"form">) {
  const [errorMsg, setErrorMsg] = useState<string | null>(null);
  const [successMsg, setSuccessMsg] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const [fieldErrors, setFieldErrors] = useState<
    Partial<Record<"email", string>>
  >({});
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    setMounted(true);
  }, []);

  const handleClearFieldError = (field: "email") => {
    setFieldErrors((prev) => clearFieldError(prev, field));
  };

  async function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setErrorMsg(null);
    setSuccessMsg(null);

    const formData = new FormData(event.currentTarget);
    const email = String(formData.get("email") ?? "").trim();

    const nextFieldErrors: Partial<Record<"email", string>> = {};
    const emailError = validateEmail(email);
    if (emailError) nextFieldErrors.email = emailError;

    if (Object.keys(nextFieldErrors).length > 0) {
      setFieldErrors(nextFieldErrors);
      return;
    }

    setFieldErrors({});
    setLoading(true);

    try {
      // TODO: Replace with actual API endpoint when available
      const response = await fetch(`/api/forgot-password`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Accept: "application/json",
        },
        body: JSON.stringify({ email }),
        credentials: "include",
      });

      if (!response.ok) {
        const contentType = response.headers.get("content-type") ?? "";
        let upstreamMessage: string | null = null;

        if (contentType.includes("application/json")) {
          const body = await response.json().catch(() => null);
          const message =
            typeof body?.error === "string"
              ? body.error
              : typeof body?.message === "string"
              ? body.message
              : null;
          upstreamMessage = message?.trim() || null;
        } else {
          const text = await response.text().catch(() => "");
          upstreamMessage = text.trim() || null;
        }

        const fallbackMessage =
          response.status >= 500
            ? "Service is unavailable. Please try again later."
            : "Unable to send reset link. Please check your email and try again.";

        const finalMessage = upstreamMessage || fallbackMessage;
        console.error(`Password reset failed (${response.status}):`, finalMessage);
        setErrorMsg(finalMessage);
        return;
      }

      setSuccessMsg("If an account exists with this email, a password reset link has been sent.");
    } catch (err: any) {
      console.error("Unexpected error:", err);
      setErrorMsg("Unexpected error connecting to server.");
    } finally {
      setLoading(false);
    }
  }

  return (
    <form
      className={cn("flex flex-col gap-4", className)}
      {...props}
      method="post"
      noValidate
      onSubmit={handleSubmit}
    >
      {errorMsg && (
        <AlertMessage
          type="error"
          message={errorMsg}
          onDismiss={() => setErrorMsg(null)}
          className="animate-[fadeIn_0.3s_ease-in-out,slideDown_0.3s_ease-in-out]"
        />
      )}

      {successMsg && (
        <AlertMessage
          type="success"
          message={successMsg}
          className="animate-[fadeIn_0.3s_ease-in-out,slideDown_0.3s_ease-in-out]"
        />
      )}

      {/* Field card */}
      <div
        className={`overflow-hidden rounded-xl border border-slate-100 bg-slate-50/60 transition-all duration-500 delay-100 ${
          mounted ? "opacity-100 translate-y-0" : "opacity-0 translate-y-3"
        }`}
      >
        <div className="px-3.5 pt-3.5 pb-3.5">
          <Field>
            <FieldLabel
              htmlFor="email"
              className="mb-1.5 block text-[10px] font-semibold uppercase tracking-widest text-slate-400"
            >
              Email
            </FieldLabel>
            <div className="group relative">
              <Mail className="absolute left-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-slate-400 transition-colors duration-200 group-focus-within:text-[#428B4D]" />
              <Input
                id="email"
                type="email"
                name="email"
                placeholder="you@example.com"
                required
                disabled={loading}
                aria-invalid={Boolean(fieldErrors.email)}
                onInput={() => handleClearFieldError("email")}
                className={cn(
                  "pl-9 h-9 rounded-lg border-slate-200 bg-white/80 text-sm placeholder:text-slate-400",
                  "shadow-sm transition-all duration-200",
                  "focus-visible:bg-white focus-visible:ring-2 focus-visible:ring-[#428B4D]/20 focus-visible:shadow-none",
                  fieldErrors.email && "border-red-300 bg-red-50/40 focus-visible:ring-red-200 focus-visible:border-red-400"
                )}
              />
            </div>
            {fieldErrors.email && (
              <p className="mt-1.5 flex items-center gap-1.5 text-[10px] text-red-500 animate-[fadeIn_0.2s_ease-in-out]">
                <span className="inline-block h-1 w-1 rounded-full bg-red-400 flex-shrink-0" />
                {fieldErrors.email}
              </p>
            )}
          </Field>
        </div>
      </div>

      {/* Submit button */}
      <div
        className={`transition-all duration-500 delay-200 ${
          mounted ? "opacity-100 translate-y-0" : "opacity-0 translate-y-3"
        }`}
      >
        <Button
          type="submit"
          disabled={loading}
          className={cn(
            "relative w-full overflow-hidden rounded-xl h-9 text-xs font-bold uppercase tracking-[0.3em] text-white",
            "transition-all duration-300 hover:scale-[1.015] hover:brightness-110 active:scale-[0.99]",
            "disabled:opacity-60 disabled:hover:scale-100 disabled:hover:brightness-100 disabled:cursor-not-allowed",
          )}
          style={{
            background: `linear-gradient(135deg, ${PRIMARY_COLOR} 0%, ${PRIMARY_COLOR_HOVER} 100%)`,
            boxShadow: "0 4px 18px -2px rgba(66,139,77,0.40)",
          }}
        >
          {!loading && (
            <span
              className="pointer-events-none absolute inset-0 -translate-x-full skew-x-[-12deg] bg-white/20"
              style={{ animation: "shimmer 2.4s ease-in-out infinite" }}
              aria-hidden
            />
          )}
          {loading ? (
            <span className="relative flex items-center justify-center gap-2">
              <Loader2 className="h-3.5 w-3.5 animate-spin" />
              Sending…
            </span>
          ) : (
            <span className="relative">Send Reset Link</span>
          )}
        </Button>
      </div>

      {/* Back to sign in */}
      <p
        className={`text-center text-[11px] text-slate-400 transition-all duration-500 delay-300 ${
          mounted ? "opacity-100 translate-y-0" : "opacity-0 translate-y-3"
        }`}
      >
        Remember your password?{" "}
        <a
          href="/login"
          className="font-semibold text-[#428B4D] underline-offset-4 hover:underline transition-colors duration-200"
        >
          Sign in
        </a>
      </p>
    </form>
  );
}
