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

import type { components } from "../api/schema";
import { LabelEditor } from "./label-editor";
import { DeleteConfirmDialog } from "./delete-confirm-dialog";
import { MutationError } from "./mutation-error";
import { ExternalUriLink } from "./external-uri-link";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { labelText } from "../lib/labels";

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

export type RecordLike = { id: string; labels: LabelView[]; external_uri: string | null };

/** One labelled record (term/authority): a display row with edit + delete, or an
 *  inline editor. All variance (mutation hooks, arg shapes, delete-confirm key) is
 *  supplied by the caller via callbacks/state — see term-row.tsx / authority-row.tsx. */
export function LabelledRecordRow({
  record,
  lang,
  deleteConfirmKey,
  savePending,
  saveError,
  onEditOpen,
  onSave,
  onDelete,
}: {
  record: RecordLike;
  lang: string;
  deleteConfirmKey: string;
  savePending: boolean;
  saveError: unknown;
  onEditOpen: () => void;
  onSave: (labels: LabelInput[], uri: string | null, done: () => void) => void;
  onDelete: () => Promise<void>;
}) {
  const { t } = useTranslation();
  const uriId = useId();

  const [editing, setEditing] = useState(false);
  const [labels, setLabels] = useState<LabelInput[]>(record.labels as LabelInput[]);
  const [uri, setUri] = useState(record.external_uri ?? "");

  if (editing) {
    return (
      <li className="space-y-2 border-b py-2">
        <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>
        <div className="flex gap-2">
          <Button
            type="button"
            size="sm"
            disabled={savePending}
            onClick={() => onSave(labels, uri.trim() || null, () => setEditing(false))}
          >
            {t("actions.save")}
          </Button>
          <Button type="button" variant="ghost" size="sm" onClick={() => setEditing(false)}>
            {t("form.cancel")}
          </Button>
        </div>
        <MutationError error={saveError} />
      </li>
    );
  }

  return (
    <li className="flex items-center gap-2 border-b py-1 text-sm">
      <div className="flex-1">
        <div>{labelText(record.labels, lang)}</div>
        {record.external_uri && <ExternalUriLink uri={record.external_uri} />}
      </div>
      <Button
        type="button"
        variant="ghost"
        size="sm"
        onClick={() => {
          onEditOpen();
          setLabels(record.labels as LabelInput[]);
          setUri(record.external_uri ?? "");
          setEditing(true);
        }}
      >
        {t("actions.edit")}
      </Button>
      <DeleteConfirmDialog description={t(deleteConfirmKey)} onConfirm={onDelete} />
    </li>
  );
}
