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

import type { components } from "../api/schema";
import { useTerms, useAddTerm } from "../api/queries";
import { LabelEditor } from "../components/label-editor";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { labelText } from "../lib/labels";

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

export function VocabularyTerms() {
  const { t, i18n } = useTranslation();

  const { id } = useParams();

  const lang = i18n.language.startsWith("sv") ? "sv" : "en";

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

  const addTerm = useAddTerm();

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

  const [uri, setUri] = useState("");

  const [error, setError] = useState(false);

  if (!id) return null;

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

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

    setError(false);

    addTerm.mutate(
      { vocabularyId: id, external_uri: uri.trim() || null, labels },
      { onSuccess: () => { setLabels([]); setUri(""); } },
    );
  };

  return (
    <div className="overflow-auto p-4">
      <h3 className="mb-2 text-sm font-medium uppercase text-neutral-500">
        {t("vocab.terms")}
      </h3>
      <ul className="mb-4">
        {isLoading && (
          <li className="text-sm text-neutral-400">…</li>
        )}
        {isError && (
          <li className="text-sm text-red-600">{t("vocab.loadError")}</li>
        )}
        {!isLoading && !isError && terms?.length === 0 && (
          <li className="text-sm text-neutral-500">{t("vocab.noTerms")}</li>
        )}
        {terms?.map((term) => (
          <li key={term.id} className="border-b py-1 text-sm">
            {labelText(term.labels, lang)}
          </li>
        ))}
      </ul>
      <form onSubmit={onAdd} className="space-y-2 border-t pt-3">
        <div className="text-sm font-medium">{t("vocab.addTerm")}</div>
        <LabelEditor value={labels} onChange={setLabels} />
        <div className="space-y-1">
          <Label htmlFor="term-uri">{t("labels.externalUri")}</Label>
          <Input
            id="term-uri"
            value={uri}
            onChange={(e) => setUri(e.target.value)}
          />
        </div>
        {error && (
          <p role="alert" className="text-xs text-red-600">
            {t("form.required")}
          </p>
        )}
        {addTerm.isError && (
          <p role="alert" className="text-xs text-red-600">
            {t("form.rejected")}
          </p>
        )}
        <Button type="submit" size="sm" disabled={addTerm.isPending}>
          {t("vocab.addTerm")}
        </Button>
      </form>
    </div>
  );
}
