"use client";

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

export default function RegisterPage() {
  const router = useRouter();
  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 = Object.fromEntries(new FormData(e.currentTarget));
    setLoading(true);
    setError(null);
    setFields({});
    try {
      await api.post("/auth/register", form);
      router.replace("/dashboard");
    } catch (err) {
      if (err instanceof ApiError) {
        setFields(err.fields);
        if (!Object.keys(err.fields).length) setError(err.message);
      } else setError("Could not reach the server. Check your connection and try again.");
      setLoading(false);
    }
  }

  return (
    <>
      <h1 className="text-2xl font-semibold tracking-[-0.01em] text-ink">Create your account</h1>
      <p className="mt-1 text-sm text-muted">You&apos;ll be the owner of your business workspace and can invite your team later.</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="Your name" htmlFor="name" error={fields.name}>
          <Input id="name" name="name" autoComplete="name" required invalid={!!fields.name} autoFocus />
        </Field>
        <Field label="Business name" htmlFor="company" error={fields.company}>
          <Input id="company" name="company" autoComplete="organization" required invalid={!!fields.company} />
        </Field>
        <Field label="Work email" htmlFor="email" error={fields.email}>
          <Input id="email" name="email" type="email" autoComplete="email" required invalid={!!fields.email} />
        </Field>
        <Field label="Password" htmlFor="password" error={fields.password} hint="At least 10 characters, with a letter and a number.">
          <Input id="password" name="password" type="password" autoComplete="new-password" required invalid={!!fields.password} />
        </Field>
        <Button type="submit" variant="primary" loading={loading} className="w-full">
          Create account
        </Button>
      </form>
      <p className="mt-6 text-sm text-muted">
        Already have an account?{" "}
        <Link href="/login" className="font-medium text-teal hover:underline">
          Sign in
        </Link>
      </p>
    </>
  );
}
