import { useId, useState, type FormEvent, type ReactNode } from "react";
import { useTranslation } from "react-i18next";

import type { components } from "../api/schema";
import { LabelEditor } from "./label-editor";
import { MutationError } from "./mutation-error";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";

type LabelInput = components["schemas"]["LabelInput"];

/** Create form for a labelled record (term/authority): single-language label +
 *  optional external URI, with required-label validation and a status-aware error.
 *  `onCreate` performs the mutation and is handed a `reset` to clear the inputs on success. */
export function LabelledRecordCreateForm({
  heading,
  submitLabel,
  pending,
  error,
  onCreate,
}: {
  heading: ReactNode;
  submitLabel: string;
  pending: boolean;
  error: unknown;
  onCreate: (labels: LabelInput[], uri: string | null, reset: () => void) => void;
}) {
  const { t } = useTranslation();
  const uriId = useId();

  const [labels, setLabels] = useState<LabelInput[]>([]);
  const [uri, setUri] = useState("");
  const [requiredError, setRequiredError] = useState(false);

  const onSubmit = (event: FormEvent) => {
    event.preventDefault();

    if (!labels.some((l) => l.label)) {
      setRequiredError(true);
      return;
    }

    setRequiredError(false);
    onCreate(labels, uri.trim() || null, () => {
      setLabels([]);
      setUri("");
    });
  };

  return (
    <form onSubmit={onSubmit} className="space-y-2 border-t pt-3">
      <div className="text-sm font-medium">{heading}</div>
      <LabelEditor value={labels} onChange={setLabels} />
      <div className="space-y-1">
        <Label htmlFor={uriId}>{t("labels.externalUri")}</Label>
        <Input
          id={uriId}
          type="url"
          placeholder={t("labels.uriPlaceholder")}
          value={uri}
          onChange={(e) => setUri(e.target.value)}
        />
      </div>
      {requiredError && (
        <p role="alert" className="text-xs text-destructive">
          {t("form.required")}
        </p>
      )}
      <MutationError error={error} />
      <Button type="submit" size="sm" disabled={pending}>
        {submitLabel}
      </Button>
    </form>
  );
}
