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

import type { components } from "../api/schema";
import {
  useCreateFieldDefinition,
  useUpdateFieldDefinition,
  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"];
type FieldDefinitionView = components["schemas"]["FieldDefinitionView"];

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

export function FieldForm({
  editing,
  onDone,
}: {
  editing: FieldDefinitionView | null;
  onDone: () => void;
}) {
  const { t } = useTranslation();
  const create = useCreateFieldDefinition();
  const update = useUpdateFieldDefinition();
  const { data: vocabularies } = useVocabularies();

  const isEdit = editing !== null;

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

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

    const hasLabel = labels.some((l) => l.label);

    if (!hasLabel || (!isEdit && !key.trim()) || (!isEdit && dataType === "term" && !vocabularyId)) {
      setError(true);
      return;
    }

    setError(false);

    if (isEdit) {
      update.mutate(
        { key: editing.key, required, group: group.trim() || null, labels },
        { onSuccess: onDone },
      );
    } else {
      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: () => {
            setKey("");
            setLabels([]);
            setDataType("text");
            setVocabularyId("");
            setAuthorityKind("");
            setGroup("");
            setRequired(false);
            setError(false);
            onDone();
          },
        },
      );
    }
  };

  const pending = isEdit ? update.isPending : create.isPending;
  const failed = isEdit ? update.isError : create.isError;

  return (
    <form onSubmit={onSubmit} className="space-y-3 overflow-auto p-4">
      <div className="flex items-center justify-between">
        <div className="text-sm font-medium">
          {isEdit ? labelTextOrKey(editing) : t("fields.newField")}
        </div>
        {isEdit && (
          <Button type="button" variant="ghost" size="sm" onClick={onDone}>
            {t("form.cancel")}
          </Button>
        )}
      </div>

      <div className="space-y-1">
        <Label htmlFor="field-key">{t("fields.key")}</Label>
        <Input
          id="field-key"
          value={key}
          disabled={isEdit}
          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}
          disabled={isEdit}
          onChange={(e) => setDataType(e.target.value)}
          className="w-full rounded border px-2 py-1 text-sm disabled:opacity-60"
        >
          {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}
            disabled={isEdit}
            onChange={(e) => setVocabularyId(e.target.value)}
            className="w-full rounded border px-2 py-1 text-sm disabled:opacity-60"
          >
            <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}
            disabled={isEdit}
            onChange={(e) => setAuthorityKind(e.target.value)}
            className="w-full rounded border px-2 py-1 text-sm disabled:opacity-60"
          >
            <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>
      )}
      {failed && (
        <p role="alert" className="text-xs text-red-600">
          {t("form.rejected")}
        </p>
      )}

      <Button type="submit" size="sm" disabled={pending}>
        {isEdit ? t("actions.save") : t("fields.create")}
      </Button>
    </form>
  );
}

function labelTextOrKey(def: FieldDefinitionView): string {
  return def.labels[0]?.label ?? def.key;
}
