import { useParams } from "react-router-dom";
import { useTranslation } from "react-i18next";

import { useTerms, useAddTerm, useVocabularies } from "../api/queries";
import { useLang } from "../lib/use-lang";
import { useBreadcrumb } from "../shell/use-breadcrumb";
import { FilteredRecordList } from "../components/filtered-record-list";
import { LabelledRecordCreateForm } from "../components/labelled-record-create-form";
import { TermRow } from "./term-row";

export function VocabularyTerms() {
  const { t } = useTranslation();
  const { id } = useParams();
  const lang = useLang();

  const { data: terms, isLoading, isError } = useTerms(id);
  const addTerm = useAddTerm();

  const { data: vocabularies } = useVocabularies();
  const vocabKey = vocabularies?.find((v) => v.id === id)?.key;

  useBreadcrumb(
    vocabKey
      ? [{ label: t("nav.vocabularies"), to: "/vocabularies" }, { label: vocabKey }]
      : [{ label: t("nav.vocabularies"), to: "/vocabularies" }],
  );

  if (!id) return null;

  return (
    <div className="overflow-auto p-4">
      <div className="mb-2 label-caption">{t("vocab.terms")}</div>

      <FilteredRecordList
        records={terms}
        lang={lang}
        isLoading={isLoading}
        isError={isError}
        loadErrorText={t("vocab.loadError")}
        emptyText={t("vocab.noTerms")}
        renderRow={(term) => <TermRow vocabularyId={id} term={term} lang={lang} />}
      />

      <LabelledRecordCreateForm
        heading={t("vocab.addTerm")}
        submitLabel={t("vocab.addTerm")}
        pending={addTerm.isPending}
        error={addTerm.error}
        onCreate={(labels, uri, reset) =>
          addTerm.mutate({ vocabularyId: id, external_uri: uri, labels }, { onSuccess: reset })}
      />
    </div>
  );
}
