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 { MutationError } from "../components/mutation-error";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Checkbox } from "@/components/ui/checkbox";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";

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;

  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 value={dataType} onValueChange={(v) => setDataType(v ?? "")} disabled={isEdit}>
          <SelectTrigger id="field-type">
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            {TYPES.map((type) => (
              <SelectItem key={type} value={type}>
                {t(`fields.types.${type}`)}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>

      {dataType === "term" && (
        <div className="space-y-1">
          <Label htmlFor="field-vocab">{t("fields.vocabulary")}</Label>
          <Select
            value={vocabularyId}
            onValueChange={(v) => setVocabularyId(v ?? "")}
            disabled={isEdit}
          >
            <SelectTrigger id="field-vocab">
              <SelectValue placeholder={t("form.selectPlaceholder")} />
            </SelectTrigger>
            <SelectContent>
              {vocabularies?.map((vocab) => (
                <SelectItem key={vocab.id} value={vocab.id}>
                  {vocab.key}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
      )}

      {dataType === "authority" && (
        <div className="space-y-1">
          <Label htmlFor="field-kind">{t("fields.authorityKind")}</Label>
          <Select
            value={authorityKind}
            onValueChange={(v) => setAuthorityKind(v ?? "")}
            disabled={isEdit}
          >
            <SelectTrigger id="field-kind">
              <SelectValue placeholder={t("fields.anyKind")} />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="">{t("fields.anyKind")}</SelectItem>
              {KINDS.map((kind) => (
                <SelectItem key={kind} value={kind}>
                  {t(`authorities.${kind}`)}
                </SelectItem>
              ))}
            </SelectContent>
          </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-destructive">
          {t("form.required")}
        </p>
      )}
      <MutationError error={isEdit ? update.error : create.error} />

      <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;
}
