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

import { useAuthorities, useCreateAuthority } from "../api/queries";
import { FilteredRecordList } from "../components/filtered-record-list";
import { LabelledRecordCreateForm } from "../components/labelled-record-create-form";
import { PageTitle } from "@/components/ui/page-title";
import { AuthorityRow } from "./authority-row";
import { useLang } from "../lib/use-lang";
import { segmentClass } from "../lib/class-recipes";
import { useDocumentTitle } from "../lib/use-document-title";
import { useBreadcrumb } from "../shell/use-breadcrumb";

const KINDS = ["person", "organisation", "place"] as const;

export function AuthoritiesPage() {
  const { t } = useTranslation();
  const { kind } = useParams();
  const lang = useLang();

  const isValidKind = (KINDS as readonly string[]).includes(kind ?? "");
  const currentKind = isValidKind ? (kind as string) : "person";

  const { data: authorities, isLoading, isError } = useAuthorities(currentKind);
  const create = useCreateAuthority();

  useDocumentTitle(t("nav.authorities"));
  useBreadcrumb([{ label: t("nav.authorities") }]);

  if (!isValidKind) return <Navigate to="/authorities/person" replace />;

  return (
    <div className="overflow-auto p-4">
      <PageTitle className="mb-3">{t("nav.authorities")}</PageTitle>
      <nav aria-label={t("nav.authorities")} className="mb-3 flex gap-2">
        {KINDS.map((k) => (
          <NavLink
            key={k}
            to={`/authorities/${k}`}
            className={({ isActive }) => segmentClass(isActive, "px-3 py-1 text-sm")}
          >
            {t(`authorities.${k}`)}
          </NavLink>
        ))}
      </nav>

      <FilteredRecordList
        records={authorities}
        lang={lang}
        isLoading={isLoading}
        isError={isError}
        loadErrorText={t("authorities.loadError")}
        emptyText={t("authorities.empty")}
        renderRow={(a) => <AuthorityRow authority={a} kind={currentKind} lang={lang} />}
      />

      <LabelledRecordCreateForm
        heading={`${t("authorities.new")} · ${t(`authorities.${currentKind}`)}`}
        submitLabel={t("authorities.create")}
        pending={create.isPending}
        error={create.error}
        onCreate={(labels, uri, reset) =>
          create.mutate({ kind: currentKind, external_uri: uri, labels }, { onSuccess: reset })}
      />
    </div>
  );
}
