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

import type { components } from "../api/schema";
import { useUpdateTerm, useDeleteTerm } from "../api/queries";
import { LabelEditor } from "../components/label-editor";
import { DeleteConfirmDialog } from "../components/delete-confirm-dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { labelText } from "../lib/labels";

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

export function TermRow({ vocabularyId, term, lang }: { vocabularyId: string; term: TermView; lang: string }) {
  const { t } = useTranslation();

  const updateTerm = useUpdateTerm();
  const deleteTerm = useDeleteTerm();

  const [editing, setEditing] = useState(false);
  const [labels, setLabels] = useState<LabelInput[]>(term.labels as LabelInput[]);
  const [uri, setUri] = useState(term.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={`term-uri-${term.id}`}>{t("labels.externalUri")}</Label>
          <Input id={`term-uri-${term.id}`} value={uri} onChange={(e) => setUri(e.target.value)} />
        </div>
        <div className="flex gap-2">
          <Button
            type="button"
            size="sm"
            disabled={updateTerm.isPending}
            onClick={() =>
              updateTerm.mutate(
                { vocabularyId, termId: term.id, external_uri: uri.trim() || null, labels },
                { onSuccess: () => setEditing(false) },
              )
            }
          >
            {t("actions.save")}
          </Button>
          <Button type="button" variant="ghost" size="sm" onClick={() => setEditing(false)}>
            {t("form.cancel")}
          </Button>
        </div>
      </li>
    );
  }

  return (
    <li className="flex items-center gap-2 border-b py-1 text-sm">
      <span className="flex-1">{labelText(term.labels, lang)}</span>
      <Button
        type="button"
        variant="ghost"
        size="sm"
        onClick={() => {
          setLabels(term.labels as LabelInput[]);
          setUri(term.external_uri ?? "");
          setEditing(true);
        }}
      >
        {t("actions.edit")}
      </Button>
      <DeleteConfirmDialog
        description={t("actions.confirmDeleteTerm")}
        onConfirm={() => deleteTerm.mutateAsync({ vocabularyId, termId: term.id })}
      />
    </li>
  );
}
