"use client";

import { useActionState, useState, type FormEvent, type ReactNode } from "react";
import { Button } from "@/components/ui/button";
import { ButtonLink } from "@/components/ui/button-link";
import { Card } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  REGISTRAR_MAX_LENGTH,
  domainFormValues,
  validateDomain,
  type DomainField,
  type DomainFieldErrors,
  type DomainFormValues,
} from "@/lib/validation/domain";
import type { DomainFormState } from "@/app/(dashboard)/domains/actions";

type DomainFormProps = {
  action: (prev: DomainFormState, formData: FormData) => Promise<DomainFormState>;
  initialValues?: DomainFormValues;
  /** Edit: the domain is fixed and shown read-only. */
  fixedName?: string;
  /** Edit: whether the registry publishes an expiry date for this domain. */
  registryHasExpiry?: boolean;
  submitLabel: string;
};

const EMPTY_VALUES: DomainFormValues = { name: "", registrar: "", manualExpiresOn: "" };

function Field({ id, label, required, hint, error, children }: {
  id: DomainField;
  label: string;
  required?: boolean;
  hint?: ReactNode;
  error?: string;
  children: ReactNode;
}) {
  return (
    <div className="space-y-1.5">
      <Label htmlFor={id}>
        {label}
        {required && (
          <span className="ml-0.5 text-red-600" aria-hidden>
            *
          </span>
        )}
      </Label>
      {children}
      {error ? (
        <p id={`${id}-error`} className="text-xs text-red-600">
          {error}
        </p>
      ) : (
        hint && <p className="text-xs text-slate-500">{hint}</p>
      )}
    </div>
  );
}

export function DomainForm({ action, initialValues, fixedName, registryHasExpiry, submitLabel }: DomainFormProps) {
  const [state, formAction, pending] = useActionState(action, {});
  const [clientErrors, setClientErrors] = useState<DomainFieldErrors | null>(null);

  const values = state.values ?? initialValues ?? EMPTY_VALUES;
  const errors = clientErrors ?? state.fieldErrors ?? {};

  // Same rules as the server; this only saves a round trip.
  function handleSubmit(event: FormEvent<HTMLFormElement>) {
    const result = validateDomain(domainFormValues(new FormData(event.currentTarget)), { requireName: !fixedName });
    if (result.ok) {
      setClientErrors(null);
      return;
    }
    event.preventDefault();
    setClientErrors(result.fieldErrors);
    const firstInvalid = Object.keys(result.fieldErrors)[0];
    if (firstInvalid) event.currentTarget.querySelector<HTMLElement>(`#${firstInvalid}`)?.focus();
  }

  const invalid = (field: DomainField) => ({
    "aria-invalid": Boolean(errors[field]),
    "aria-describedby": errors[field] ? `${field}-error` : undefined,
  });

  return (
    <Card className="max-w-2xl p-5">
      <form action={formAction} onSubmit={handleSubmit} noValidate className="space-y-5">
        {state.error && (
          <p role="alert" className="rounded-md border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700">
            {state.error}
          </p>
        )}

        {fixedName ? (
          <div className="space-y-1.5">
            <p className="text-sm font-medium text-slate-700">Domain</p>
            <p className="text-sm text-slate-900">{fixedName}</p>
          </div>
        ) : (
          <Field
            id="name"
            label="Domain"
            required
            hint="e.g. example.com. A subdomain or URL is reduced to the registered domain."
            error={errors.name}
          >
            <Input
              id="name"
              name="name"
              defaultValue={values.name}
              placeholder="example.com"
              autoCapitalize="none"
              spellCheck={false}
              maxLength={253}
              required
              {...invalid("name")}
            />
          </Field>
        )}

        <Field id="registrar" label="Registrar / Account" hint="Where the domain is registered, e.g. GoDaddy, Cloudflare" error={errors.registrar}>
          <Input
            id="registrar"
            name="registrar"
            defaultValue={values.registrar}
            maxLength={REGISTRAR_MAX_LENGTH}
            {...invalid("registrar")}
          />
        </Field>

        <Field
          id="manualExpiresOn"
          label="Expiry Date (manual)"
          hint={
            registryHasExpiry
              ? "The registry publishes this domain's expiry date, which is used instead. Only needed if it stops publishing one."
              : "Only for registries that don't publish an expiry date (e.g. .ch): copy it from the registrar's account. Leave empty to clear."
          }
          error={errors.manualExpiresOn}
        >
          <Input
            id="manualExpiresOn"
            name="manualExpiresOn"
            type="date"
            defaultValue={values.manualExpiresOn}
            className="w-48"
            {...invalid("manualExpiresOn")}
          />
        </Field>

        <div className="flex items-center justify-between gap-3 border-t border-slate-200 pt-4">
          <p className="text-xs text-slate-500">
            {!fixedName && (
              <>
                <span className="text-red-600">*</span> Required
              </>
            )}
          </p>
          <div className="flex items-center gap-2">
            <ButtonLink href="/domains" variant="secondary">
              Cancel
            </ButtonLink>
            <Button type="submit" disabled={pending}>
              {pending ? "Saving…" : submitLabel}
            </Button>
          </div>
        </div>
      </form>
    </Card>
  );
}
