import { ArrowDown, ArrowUp, Plus, Trash2 } from "lucide-react";
import { useEffect, useMemo, useState } from "react";
import {
  Button,
  Dialog,
  DismissibleAlert,
  FormField as Field,
  IconButton,
  ToggleSwitch,
  type ApiSettings
} from "@govoplan/core-webui";
import {
  saveFormDefinition,
  type FormDefinition,
  type FormFieldDefinition,
  type FormValueType
} from "../../api/forms";


const VALUE_TYPES: Array<{ value: FormValueType; label: string }> = [
  { value: "text", label: "Text" },
  { value: "multiline_text", label: "Long text" },
  { value: "email", label: "Email" },
  { value: "integer", label: "Integer" },
  { value: "number", label: "Number" },
  { value: "boolean", label: "Yes / no" },
  { value: "date", label: "Date" },
  { value: "datetime", label: "Date and time" },
  { value: "choice", label: "Single choice" },
  { value: "multi_choice", label: "Multiple choice" },
  { value: "object", label: "Structured object" },
  { value: "list", label: "Structured list" }
];

export default function FormDefinitionDialog({
  open,
  settings,
  tenantId,
  definition,
  canPublish,
  onClose,
  onSaved
}: {
  open: boolean;
  settings: ApiSettings;
  tenantId: string;
  definition: FormDefinition | null;
  canPublish: boolean;
  onClose: () => void;
  onSaved: (definition: FormDefinition) => void;
}) {
  const [draft, setDraft] = useState<FormDefinition>(() => initialDraft(tenantId, definition));
  const [changeReason, setChangeReason] = useState("");
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState("");

  useEffect(() => {
    if (!open) return;
    setDraft(initialDraft(tenantId, definition));
    setChangeReason("");
    setBusy(false);
    setError("");
  }, [definition, open, tenantId]);

  const valid = useMemo(() => Boolean(
    draft.title.trim()
      && draft.key.trim()
      && draft.fields.length > 0
      && draft.fields.every((field) => field.key.trim() && field.label.trim())
      && changeReason.trim()
  ), [changeReason, draft]);

  async function save() {
    if (!valid) return;
    setBusy(true);
    setError("");
    const revision = crypto.randomUUID();
    const recordedAt = new Date().toISOString();
    const payload: FormDefinition = {
      ...draft,
      reference: {
        ...draft.reference,
        version: revision
      },
      temporal: {
        ...draft.temporal,
        revision,
        recorded_at: recordedAt,
        superseded_at: null,
        change_reason: changeReason.trim()
      },
      title: draft.title.trim(),
      key: draft.key.trim(),
      description: draft.description?.trim() || null,
      fields: draft.fields.map(normalizeField),
      policy_refs: draft.policy_refs.map((item) => item.trim()).filter(Boolean),
      metadata: { ...draft.metadata }
    };
    try {
      const saved = await saveFormDefinition(
        settings,
        payload,
        definition?.reference.version
      );
      onSaved(saved);
    } catch (reason) {
      setError(reason instanceof Error ? reason.message : "The Form definition could not be saved.");
    } finally {
      setBusy(false);
    }
  }

  function patchField(index: number, patch: Partial<FormFieldDefinition>) {
    setDraft((current) => ({
      ...current,
      fields: current.fields.map((field, fieldIndex) => fieldIndex === index ? { ...field, ...patch } : field)
    }));
  }

  function moveField(index: number, delta: -1 | 1) {
    setDraft((current) => {
      const target = index + delta;
      if (target < 0 || target >= current.fields.length) return current;
      const fields = [...current.fields];
      [fields[index], fields[target]] = [fields[target], fields[index]];
      return { ...current, fields };
    });
  }

  return (
    <Dialog
      open={open}
      title={definition ? `Revise ${definition.title}` : "New Form definition"}
      onClose={onClose}
      closeDisabled={busy}
      portal
      className="form-definition-dialog"
      footer={
        <>
          <Button onClick={onClose} disabled={busy}>Cancel</Button>
          <Button variant="primary" onClick={() => void save()} disabled={busy || !valid}>
            {busy ? "Saving" : "Save revision"}
          </Button>
        </>
      }>
      <div className="form-definition-editor">
        {error && <DismissibleAlert tone="danger" resetKey={error}>{error}</DismissibleAlert>}
        <div className="form-definition-grid">
          <Field label="Title">
            <input value={draft.title} disabled={busy} onChange={(event) => setDraft({ ...draft, title: event.target.value })} />
          </Field>
          <Field label="Key">
            <input value={draft.key} disabled={busy || Boolean(definition)} onChange={(event) => setDraft({ ...draft, key: event.target.value })} />
          </Field>
          <Field label="Description" className="form-definition-wide">
            <textarea rows={3} value={draft.description ?? ""} disabled={busy} onChange={(event) => setDraft({ ...draft, description: event.target.value })} />
          </Field>
          <Field label="Publication state">
            <select value={draft.publication_state} disabled={busy} onChange={(event) => setDraft({ ...draft, publication_state: event.target.value as FormDefinition["publication_state"] })}>
              {definition?.publication_state !== "published" && <option value="draft">Draft</option>}
              {canPublish && <option value="published">Published</option>}
              {canPublish && <option value="retired">Retired</option>}
            </select>
          </Field>
          <Field label="Signature">
            <select value={draft.signature_requirement} disabled={busy} onChange={(event) => setDraft({ ...draft, signature_requirement: event.target.value as FormDefinition["signature_requirement"] })}>
              <option value="none">Not used</option>
              <option value="optional">Optional</option>
              <option value="required">Required</option>
            </select>
          </Field>
          <Field label="Maximum attachments">
            <input type="number" min={0} max={1000} value={draft.max_attachments} disabled={busy} onChange={(event) => setDraft({ ...draft, max_attachments: Number(event.target.value) })} />
          </Field>
          <div className="form-definition-toggle">
            <ToggleSwitch label="Draft saving" checked={draft.allow_drafts} disabled={busy} onChange={(allow_drafts) => setDraft({ ...draft, allow_drafts })} />
          </div>
          <Field label="Policy references" className="form-definition-wide">
            <input value={draft.policy_refs.join(", ")} disabled={busy} placeholder="policy:permit-intake" onChange={(event) => setDraft({ ...draft, policy_refs: splitValues(event.target.value) })} />
          </Field>
          <div className="form-definition-handoffs form-definition-wide">
            <span>Permitted handoffs</span>
            {(["case", "workflow", "record"] as const).map((kind) =>
              <ToggleSwitch
                key={kind}
                label={humanize(kind)}
                checked={draft.handoff_kinds.includes(kind)}
                disabled={busy}
                onChange={(checked) => setDraft({
                  ...draft,
                  handoff_kinds: checked
                    ? [...draft.handoff_kinds, kind]
                    : draft.handoff_kinds.filter((item) => item !== kind)
                })}
              />
            )}
          </div>
        </div>

        <div className="form-field-editor-heading">
          <h3>Fields</h3>
          <Button onClick={() => setDraft({ ...draft, fields: [...draft.fields, emptyField(draft.fields.length + 1)] })} disabled={busy}>
            <Plus size={16} aria-hidden="true" />Add field
          </Button>
        </div>
        <div className="form-field-editor-list">
          {draft.fields.map((field, index) =>
            <div className="form-field-editor-row" key={`${index}:${field.key}`}>
              <div className="form-field-order">
                <IconButton label={`Move ${field.label || "field"} up`} icon={<ArrowUp size={15} />} disabled={busy || index === 0} onClick={() => moveField(index, -1)} />
                <IconButton label={`Move ${field.label || "field"} down`} icon={<ArrowDown size={15} />} disabled={busy || index === draft.fields.length - 1} onClick={() => moveField(index, 1)} />
              </div>
              <Field label="Key"><input value={field.key} disabled={busy} onChange={(event) => patchField(index, { key: event.target.value })} /></Field>
              <Field label="Label"><input value={field.label} disabled={busy} onChange={(event) => patchField(index, { label: event.target.value })} /></Field>
              <Field label="Type">
                <select value={field.value_type} disabled={busy} onChange={(event) => patchField(index, { value_type: event.target.value as FormValueType, options: isChoice(event.target.value) ? field.options : [] })}>
                  {VALUE_TYPES.map((type) => <option key={type.value} value={type.value}>{type.label}</option>)}
                </select>
              </Field>
              <div className="form-field-required"><ToggleSwitch label="Required" checked={field.required} disabled={busy} onChange={(required) => patchField(index, { required })} /></div>
              <Field label="Help text" className="form-field-help"><input value={field.help_text ?? ""} disabled={busy} onChange={(event) => patchField(index, { help_text: event.target.value })} /></Field>
              {isChoice(field.value_type) &&
                <Field label="Options" className="form-field-options"><input value={field.options.join(", ")} disabled={busy} onChange={(event) => patchField(index, { options: splitValues(event.target.value) })} /></Field>
              }
              <ConstraintFields field={field} disabled={busy} onChange={(constraints) => patchField(index, { constraints })} />
              <IconButton
                label={`Remove ${field.label || "field"}`}
                icon={<Trash2 size={16} />}
                variant="danger"
                disabled={busy || draft.fields.length === 1}
                onClick={() => setDraft({ ...draft, fields: draft.fields.filter((_, fieldIndex) => fieldIndex !== index) })}
              />
            </div>
          )}
        </div>
        <Field label="Change reason">
          <input value={changeReason} disabled={busy} maxLength={1000} onChange={(event) => setChangeReason(event.target.value)} placeholder="Why is this revision needed?" />
        </Field>
      </div>
    </Dialog>
  );
}

function ConstraintFields({ field, disabled, onChange }: { field: FormFieldDefinition; disabled: boolean; onChange: (value: Record<string, unknown>) => void }) {
  if (["text", "multiline_text", "email"].includes(field.value_type)) {
    return (
      <div className="form-field-constraints">
        <Field label="Minimum length"><input type="number" min={0} value={constraintValue(field.constraints.min_length)} disabled={disabled} onChange={(event) => onChange(patchConstraint(field.constraints, "min_length", event.target.value))} /></Field>
        <Field label="Maximum length"><input type="number" min={0} value={constraintValue(field.constraints.max_length)} disabled={disabled} onChange={(event) => onChange(patchConstraint(field.constraints, "max_length", event.target.value))} /></Field>
        <Field label="Pattern"><input value={String(field.constraints.pattern ?? "")} disabled={disabled} onChange={(event) => onChange(patchTextConstraint(field.constraints, "pattern", event.target.value))} /></Field>
      </div>
    );
  }
  if (["integer", "number"].includes(field.value_type)) {
    return (
      <div className="form-field-constraints">
        <Field label="Minimum"><input type="number" value={constraintValue(field.constraints.minimum)} disabled={disabled} onChange={(event) => onChange(patchConstraint(field.constraints, "minimum", event.target.value))} /></Field>
        <Field label="Maximum"><input type="number" value={constraintValue(field.constraints.maximum)} disabled={disabled} onChange={(event) => onChange(patchConstraint(field.constraints, "maximum", event.target.value))} /></Field>
      </div>
    );
  }
  return null;
}

function initialDraft(tenantId: string, definition: FormDefinition | null): FormDefinition {
  if (definition) return structuredClone(definition);
  const id = crypto.randomUUID();
  const revision = crypto.randomUUID();
  const now = new Date().toISOString();
  return {
    reference: { kind: "form", owner_module: "forms", object_id: id, tenant_id: tenantId, version: revision },
    key: "",
    temporal: { revision, recorded_at: now, change_reason: "" },
    title: "",
    description: "",
    fields: [emptyField(1)],
    publication_state: "draft",
    allow_drafts: true,
    max_attachments: 0,
    signature_requirement: "none",
    policy_refs: [],
    handoff_kinds: [],
    metadata: {}
  };
}

function emptyField(index: number): FormFieldDefinition {
  return { key: `field-${index}`, label: "", value_type: "text", required: false, help_text: "", options: [], constraints: {} };
}

function normalizeField(field: FormFieldDefinition): FormFieldDefinition {
  return {
    ...field,
    key: field.key.trim(),
    label: field.label.trim(),
    help_text: field.help_text?.trim() || null,
    options: isChoice(field.value_type) ? field.options.map((item) => item.trim()).filter(Boolean) : [],
    constraints: Object.fromEntries(Object.entries(field.constraints).filter(([, value]) => value !== "" && value !== null && value !== undefined))
  };
}

function splitValues(value: string): string[] {
  return value.split(",").map((item) => item.trim()).filter(Boolean);
}

function isChoice(value: string): boolean {
  return value === "choice" || value === "multi_choice";
}

function patchConstraint(current: Record<string, unknown>, key: string, value: string): Record<string, unknown> {
  const next = { ...current };
  if (!value.trim()) delete next[key];
  else next[key] = Number(value);
  return next;
}

function patchTextConstraint(current: Record<string, unknown>, key: string, value: string): Record<string, unknown> {
  const next = { ...current };
  if (!value) delete next[key];
  else next[key] = value;
  return next;
}

function constraintValue(value: unknown): number | "" {
  return typeof value === "number" ? value : "";
}

function humanize(value: string): string {
  return value.replace(/[_:.-]+/g, " ").replace(/\b\w/g, (letter) => letter.toUpperCase());
}
