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

import type { components } from "../api/schema";
import { useAuthorities, useCreateAuthority } from "../api/queries";
import { LabelEditor } from "../components/label-editor";
import { Button } from "@/components/ui/button";
import { PageTitle } from "@/components/ui/page-title";
import { ListSkeleton } from "@/components/ui/skeletons";
import { AuthorityRow } from "./authority-row";
import { useDocumentTitle } from "../lib/use-document-title";
import { useBreadcrumb } from "../shell/use-breadcrumb";

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

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

export function AuthoritiesPage() {
  const { t, i18n } = useTranslation();
  const { kind } = useParams();
  const lang = i18n.language.startsWith("sv") ? "sv" : "en";

  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();

  const [labels, setLabels] = useState<LabelInput[]>([]);
  const [error, setError] = useState(false);

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

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

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

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

    setError(false);
    create.mutate(
      { kind: kind as string, external_uri: null, labels },
      { onSuccess: () => setLabels([]) },
    );
  };

  return (
    <div className="overflow-auto p-4">
      <PageTitle className="mb-3">{t("nav.authorities")}</PageTitle>
      <div role="tablist" className="mb-3 flex gap-2">
        {KINDS.map((k) => (
          <NavLink
            key={k}
            to={`/authorities/${k}`}
            role="tab"
            aria-selected={k === currentKind}
            className={({ isActive }) =>
              `rounded-md px-3 py-1 text-sm ${isActive ? "bg-primary text-primary-foreground" : "border"}`
            }
          >
            {t(`authorities.${k}`)}
          </NavLink>
        ))}
      </div>

      {isLoading ? (
        <ListSkeleton className="mb-4" rows={5} />
      ) : (
        <ul className="mb-4">
          {isError && (
            <li className="text-sm text-destructive">{t("authorities.loadError")}</li>
          )}
          {!isError && authorities?.length === 0 && (
            <li className="text-sm text-muted-foreground">{t("authorities.empty")}</li>
          )}
          {authorities?.map((a) => (
            <AuthorityRow key={a.id} authority={a} kind={currentKind} lang={lang} />
          ))}
        </ul>
      )}

      <form onSubmit={onCreate} className="space-y-2 border-t pt-3">
        <div className="text-sm font-medium">
          {t("authorities.new")} · {t(`authorities.${currentKind}`)}
        </div>

        <LabelEditor value={labels} onChange={setLabels} />

        {error && (
          <p role="alert" className="text-xs text-destructive">
            {t("form.required")}
          </p>
        )}

        {create.isError && (
          <p role="alert" className="text-xs text-destructive">
            {t("form.rejected")}
          </p>
        )}

        <Button type="submit" size="sm" disabled={create.isPending}>
          {t("authorities.create")}
        </Button>
      </form>
    </div>
  );
}
