"use client";

import Link from "next/link";
import { useState, type FormEvent } from "react";
import { Button, Field, Input } from "@/components/ui/kit";
import { api, ApiError } from "@/lib/api";

export default function ForgotPasswordPage() {
  const [sent, setSent] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [fields, setFields] = useState<Record<string, string>>({});
  const [loading, setLoading] = useState(false);

  async function onSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault();
    const email = String(new FormData(e.currentTarget).get("email") ?? "");
    setLoading(true);
    setError(null);
    setFields({});
    try {
      await api.post("/auth/forgot-password", { email });
      setSent(email);
    } catch (err) {
      if (err instanceof ApiError && Object.keys(err.fields).length) setFields(err.fields);
      else setError(err instanceof ApiError ? err.message : "Could not reach the server. Check your connection and try again.");
    } finally {
      setLoading(false);
    }
  }

  return (
    <>
      <h1 className="text-2xl font-semibold tracking-[-0.01em] text-ink">Reset your password</h1>
      {sent ? (
        <div className="mt-6 space-y-4 text-sm">
          <p role="status" className="rounded-md bg-teal-soft px-3 py-2.5 text-teal">
            If an account exists for <strong>{sent}</strong>, we have emailed a link to choose a new password. It works for one hour.
          </p>
          <p className="text-muted">No email after a few minutes? Check your spam folder, or ask your workspace owner to make sure you are using the right address.</p>
        </div>
      ) : (
        <>
          <p className="mt-1 text-sm text-muted">Enter the email you sign in with and we&apos;ll send you a reset link.</p>
          <form onSubmit={onSubmit} className="mt-8 space-y-4" noValidate>
            {error && (
              <div role="alert" className="rounded-md bg-brick-soft px-3 py-2.5 text-sm text-brick">
                {error}
              </div>
            )}
            <Field label="Email" htmlFor="email" error={fields.email}>
              <Input id="email" name="email" type="email" autoComplete="email" invalid={!!fields.email} autoFocus />
            </Field>
            <Button type="submit" variant="primary" loading={loading} className="w-full">
              Send reset link
            </Button>
          </form>
        </>
      )}
      <p className="mt-6 text-sm text-muted">
        <Link href="/login" className="font-medium text-teal hover:underline">
          Back to sign in
        </Link>
      </p>
    </>
  );
}
