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

import type { components } from "../api/schema";
import { useCreateFieldDefinition, useVocabularies } 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 { Checkbox } from "@/components/ui/checkbox";

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

const TYPES = ["text", "localized_text", "integer", "date", "boolean", "term", "authority"] as const;
const KINDS = ["person", "organisation", "place"] as const;

export function FieldForm() {
  const { t } = useTranslation();
  const create = useCreateFieldDefinition();
  const { data: vocabularies } = useVocabularies();

  const [key, setKey] = useState("");
  const [labels, setLabels] = useState<LabelInput[]>([]);
  const [dataType, setDataType] = useState<string>("text");
  const [vocabularyId, setVocabularyId] = useState("");
  const [authorityKind, setAuthorityKind] = useState("");
  const [group, setGroup] = useState("");
  const [required, setRequired] = useState(false);
  const [error, setError] = useState(false);

  const reset = () => {
    setKey("");
    setLabels([]);
    setDataType("text");
    setVocabularyId("");
    setAuthorityKind("");
    setGroup("");
    setRequired(false);
    setError(false);
  };

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

    const hasEn = labels.some((l) => l.lang === "en" && l.label);
    const termNeedsVocab = dataType === "term" && !vocabularyId;

    if (!key.trim() || !hasEn || termNeedsVocab) {
      setError(true);
      return;
    }

    setError(false);
    create.mutate(
      {
        key: key.trim(),
        data_type: dataType,
        vocabulary_id: dataType === "term" ? vocabularyId : null,
        authority_kind: dataType === "authority" ? authorityKind || null : null,
        required,
        group: group.trim() || null,
        labels,
      },
      { onSuccess: reset },
    );
  };

  return (
    <form onSubmit={onSubmit} className="space-y-3 overflow-auto p-4">
      <div className="text-sm font-medium">{t("fields.newField")}</div>

      <div className="space-y-1">
        <Label htmlFor="field-key">{t("fields.key")}</Label>
        <Input id="field-key" value={key} onChange={(e) => setKey(e.target.value)} />
      </div>

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

      <div className="space-y-1">
        <Label htmlFor="field-type">{t("fields.type")}</Label>
        <select
          id="field-type"
          value={dataType}
          onChange={(e) => setDataType(e.target.value)}
          className="w-full rounded border px-2 py-1 text-sm"
        >
          {TYPES.map((type) => (
            <option key={type} value={type}>
              {t(`fields.types.${type}`)}
            </option>
          ))}
        </select>
      </div>

      {dataType === "term" && (
        <div className="space-y-1">
          <Label htmlFor="field-vocab">{t("fields.vocabulary")}</Label>
          <select
            id="field-vocab"
            value={vocabularyId}
            onChange={(e) => setVocabularyId(e.target.value)}
            className="w-full rounded border px-2 py-1 text-sm"
          >
            <option value="">{t("form.selectPlaceholder")}</option>
            {vocabularies?.map((vocab) => (
              <option key={vocab.id} value={vocab.id}>
                {vocab.key}
              </option>
            ))}
          </select>
        </div>
      )}

      {dataType === "authority" && (
        <div className="space-y-1">
          <Label htmlFor="field-kind">{t("fields.authorityKind")}</Label>
          <select
            id="field-kind"
            value={authorityKind}
            onChange={(e) => setAuthorityKind(e.target.value)}
            className="w-full rounded border px-2 py-1 text-sm"
          >
            <option value="">{t("fields.anyKind")}</option>
            {KINDS.map((kind) => (
              <option key={kind} value={kind}>
                {t(`authorities.${kind}`)}
              </option>
            ))}
          </select>
        </div>
      )}

      <div className="space-y-1">
        <Label htmlFor="field-group">{t("fields.group")}</Label>
        <Input id="field-group" value={group} onChange={(e) => setGroup(e.target.value)} />
      </div>

      <label className="flex items-center gap-2 text-sm">
        <Checkbox checked={required} onCheckedChange={(checked) => setRequired(checked === true)} />
        {t("fields.required")}
      </label>

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

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