"use client";

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

export function ResetPassword() {
  const token = useSearchParams().get("token") ?? "";
  const [done, setDone] = useState(false);
  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 form = new FormData(e.currentTarget);
    const password = String(form.get("password") ?? "");
    if (password !== form.get("confirm")) {
      setFields({ confirm: "The two passwords don't match" });
      return;
    }
    setLoading(true);
    setError(null);
    setFields({});
    try {
      await api.post("/auth/reset-password", { token, password });
      setDone(true);
    } 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);
    }
  }

  if (!token) {
    return (
      <>
        <h1 className="text-2xl font-semibold tracking-[-0.01em] text-ink">Reset link missing</h1>
        <p className="mt-2 text-sm text-muted">Open the link from the email exactly as it was sent, or ask for a new one.</p>
        <p className="mt-6 text-sm">
          <Link href="/forgot-password" className="font-medium text-teal hover:underline">
            Send a new link
          </Link>
        </p>
      </>
    );
  }

  return (
    <>
      <h1 className="text-2xl font-semibold tracking-[-0.01em] text-ink">Choose a new password</h1>
      {done ? (
        <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">
            Your password has been changed and every device has been signed out.
          </p>
          <Link href="/login" className="inline-block font-medium text-teal hover:underline">
            Sign in with the new password
          </Link>
        </div>
      ) : (
        <>
          <p className="mt-1 text-sm text-muted">Use at least 10 characters with a letter and a number. You&apos;ll be signed out everywhere.</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}{" "}
                <Link href="/forgot-password" className="font-medium underline">
                  Send a new link
                </Link>
              </div>
            )}
            <Field label="New password" htmlFor="password" error={fields.password}>
              <Input id="password" name="password" type="password" autoComplete="new-password" invalid={!!fields.password} autoFocus />
            </Field>
            <Field label="Repeat the new password" htmlFor="confirm" error={fields.confirm}>
              <Input id="confirm" name="confirm" type="password" autoComplete="new-password" invalid={!!fields.confirm} />
            </Field>
            <Button type="submit" variant="primary" loading={loading} className="w-full">
              Change password
            </Button>
          </form>
        </>
      )}
    </>
  );
}
