"use client";

import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { Field, FieldGroup, 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 } 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-6", className)}
      {...props}
      method="post"
      noValidate
      onSubmit={handleSubmit}
    >
      <FieldGroup>
        {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>
          <FieldLabel
            htmlFor="email"
            className={`text-xs font-semibold uppercase tracking-wide text-slate-500 transition-all duration-500 ${
              mounted ? "opacity-100 translate-x-0" : "opacity-0 -translate-x-4"
            }`}
          >
            Email
          </FieldLabel>
          <div 
            className={`relative transition-all duration-500 delay-100 ${
              mounted ? "opacity-100 translate-x-0" : "opacity-0 -translate-x-4"
            }`}
          >
            <Mail className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400 transition-colors duration-200" />
            <Input
              id="email"
              type="email"
              name="email"
              placeholder="m@example.com"
              required
              disabled={loading}
              aria-invalid={Boolean(fieldErrors.email)}
              onInput={() => handleClearFieldError("email")}
              className={cn(
                "pl-10 transition-all duration-200 focus:scale-[1.02]",
                fieldErrors.email && "border-red-300 focus-visible:ring-red-200"
              )}
            />
          </div>
          {fieldErrors.email && (
            <p className="mt-1 text-xs text-red-500 animate-[fadeIn_0.2s_ease-in-out]">
              {fieldErrors.email}
            </p>
          )}
        </Field>

        <Field>
          <Button
            type="submit"
            disabled={loading}
            className={`w-full rounded-lg px-4 py-3 text-sm font-semibold uppercase tracking-[0.3em] text-white transition-all duration-300 hover:scale-[1.02] hover:shadow-lg disabled:opacity-70 disabled:hover:scale-100 ${
              mounted ? "opacity-100 translate-y-0" : "opacity-0 translate-y-4"
            }`}
            style={{
              backgroundColor: PRIMARY_COLOR,
              transitionDelay: mounted ? "200ms" : "0ms",
            }}
            onMouseEnter={(e) => {
              if (!loading) {
                e.currentTarget.style.backgroundColor = "#357a3f";
              }
            }}
            onMouseLeave={(e) => {
              if (!loading) {
                e.currentTarget.style.backgroundColor = PRIMARY_COLOR;
              }
            }}
          >
            {loading ? (
              <span className="flex items-center justify-center gap-2">
                <Loader2 className="h-4 w-4 animate-spin" />
                Sending...
              </span>
            ) : (
              "Send Reset Link"
            )}
          </Button>
        </Field>

        <Field>
          <p 
            className={`text-center text-xs text-slate-500 transition-all duration-500 delay-300 ${
              mounted ? "opacity-100 translate-y-0" : "opacity-0 translate-y-4"
            }`}
          >
            Back to Login?{" "}
            <a
              href="/login"
              className="font-semibold hover:underline transition-all duration-200"
              style={{ color: PRIMARY_COLOR }}
              onMouseEnter={(e) => {
                e.currentTarget.style.color = "#357a3f";
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.color = PRIMARY_COLOR;
              }}
            >
              Sign In
            </a>
          </p>
        </Field>
      </FieldGroup>
    </form>
  );
}
