import { Head, router } from '@inertiajs/react';
import { GripVertical } from 'lucide-react';
import { useState } from 'react';

import HeadingSmall from '@/components/heading-small';
import AppLayout from '@/layouts/app-layout';
import { index as formSectionsIndex } from '@/routes/admin/form-sections';
import { index, sync } from '@/routes/admin/web-form-fields';

type WebFormOption = {
    id: number;
    name: string;
};

type FormFieldOption = {
    id: number;
    name: string;
    label: string;
};

type FormSectionOption = {
    id: number;
    name: string;
    label: string;
};

type AssignedSection = {
    id: number;
    name: string;
    label: string;
    description: string | null;
    order: number;
};

type BaseRow = {
    form_section_id: number | null;
    order: number;
};

type FormFieldRow = BaseRow & {
    type: 'form_field';
    id: number;
    name: string;
    label: string;
};

type UtilityFieldRow = BaseRow & {
    type: 'utility_field';
    utility_field_name: string;
};

type SupplierFieldRow = BaseRow & {
    type: 'supplier_field';
    supplier_field_name: string;
};

type AffirmationsBlockRow = BaseRow & {
    type: 'affirmations_block';
};

type RemainingUtilityFieldsBlockRow = BaseRow & {
    type: 'remaining_utility_fields_block';
};

type RemainingSupplierFieldsBlockRow = BaseRow & {
    type: 'remaining_supplier_fields_block';
};

type AssignedField =
    | FormFieldRow
    | UtilityFieldRow
    | SupplierFieldRow
    | AffirmationsBlockRow
    | RemainingUtilityFieldsBlockRow
    | RemainingSupplierFieldsBlockRow;

type Props = {
    webForms: WebFormOption[];
    formFields: FormFieldOption[];
    formSections: FormSectionOption[];
    selectedFormId: number | null;
    assignedFields: AssignedField[];
    assignedSections: AssignedSection[];
};

const UTILITY_FIELD_OPTIONS = [
    { value: 'primary_account_identifier', label: 'Primary Account Identifier' },
    { value: 'secondary_account_identifier', label: 'Secondary Account Identifier' },
    { value: 'tertiary_account_identifier', label: 'Tertiary Account Identifier' },
];

function rowKey(f: AssignedField): string {
    if (f.type === 'form_field') return `form_field_${f.id}`;
    if (f.type === 'utility_field') return `utility_field_${f.utility_field_name}`;
    if (f.type === 'supplier_field') return `supplier_field_${f.supplier_field_name}`;
    if (f.type === 'affirmations_block') return 'affirmations_block';
    if (f.type === 'remaining_utility_fields_block') return 'remaining_utility_fields_block';
    return 'remaining_supplier_fields_block';
}

/**
 * Reassigns `order` for every row, scoped per `form_section_id` group, based on each row's
 * current position in `all` — the array's traversal order is the source of truth for a
 * row's position within its own section.
 */
function renumberFields(all: AssignedField[]): AssignedField[] {
    const counts = new Map<string, number>();

    return all.map((f) => {
        const key = f.form_section_id === null ? 'null' : String(f.form_section_id);
        const next = (counts.get(key) ?? 0) + 1;
        counts.set(key, next);
        return { ...f, order: next };
    });
}

function renumberSections(all: AssignedSection[]): AssignedSection[] {
    return all.map((s, i) => ({ ...s, order: i + 1 }));
}

const breadcrumbs = [{ title: 'Web Form Fields', href: index.url() }];

export default function WebFormFields({
    webForms,
    formFields,
    formSections,
    selectedFormId,
    assignedFields,
    assignedSections,
}: Props) {
    const [sections, setSections] = useState<AssignedSection[]>(assignedSections);
    const [fields, setFields] = useState<AssignedField[]>(assignedFields);
    const [saving, setSaving] = useState(false);

    const [draggedFieldKey, setDraggedFieldKey] = useState<string | null>(null);
    const [dragOverFieldKey, setDragOverFieldKey] = useState<string | null>(null);
    const [draggedSectionId, setDraggedSectionId] = useState<number | null>(null);
    const [dragOverSectionId, setDragOverSectionId] = useState<number | null>(null);

    const assignedFormFieldIds = fields
        .filter((f): f is FormFieldRow => f.type === 'form_field')
        .map((f) => f.id);

    const assignedUtilityFieldNames = fields
        .filter((f): f is UtilityFieldRow => f.type === 'utility_field')
        .map((f) => f.utility_field_name);

    const assignedSupplierFieldNames = fields
        .filter((f): f is SupplierFieldRow => f.type === 'supplier_field')
        .map((f) => f.supplier_field_name);

    const hasAffirmationsBlock = fields.some((f) => f.type === 'affirmations_block');
    const hasRemainingUtilityFieldsBlock = fields.some((f) => f.type === 'remaining_utility_fields_block');
    const hasRemainingSupplierFieldsBlock = fields.some((f) => f.type === 'remaining_supplier_fields_block');

    const availableFormFields = formFields.filter((ff) => !assignedFormFieldIds.includes(ff.id));
    const availableUtilityFields = UTILITY_FIELD_OPTIONS.filter(
        (uf) => !assignedUtilityFieldNames.includes(uf.value),
    );
    const availableSections = formSections.filter((s) => !sections.some((as) => as.id === s.id));

    const groups: { id: number | null; label: string; name: string | null }[] = [
        { id: null, label: 'Unsectioned', name: null },
        ...sections.map((s) => ({ id: s.id, label: s.label, name: s.name })),
    ];

    function groupFields(sectionId: number | null): AssignedField[] {
        return fields.filter((f) => f.form_section_id === sectionId).sort((a, b) => a.order - b.order);
    }

    function handleFormChange(formId: string) {
        router.get(
            index.url(),
            { web_form_id: formId },
            { preserveState: false },
        );
    }

    function getTargetSectionId(): number | null {
        const select = document.getElementById('add-target-section-select') as HTMLSelectElement | null;
        return select?.value ? Number(select.value) : null;
    }

    function addRow(row: AssignedField) {
        setFields((prev) => renumberFields([...prev, row]));
    }

    function addFormField(fieldId: number) {
        const field = formFields.find((f) => f.id === fieldId);
        if (!field) return;

        addRow({ type: 'form_field', ...field, form_section_id: getTargetSectionId(), order: 0 });
    }

    function addUtilityField(utilityFieldName: string) {
        addRow({
            type: 'utility_field',
            utility_field_name: utilityFieldName,
            form_section_id: getTargetSectionId(),
            order: 0,
        });
    }

    function addSupplierField(supplierFieldName: string) {
        addRow({
            type: 'supplier_field',
            supplier_field_name: supplierFieldName,
            form_section_id: getTargetSectionId(),
            order: 0,
        });
    }

    function addAffirmationsBlock() {
        addRow({ type: 'affirmations_block', form_section_id: getTargetSectionId(), order: 0 });
    }

    function addRemainingUtilityFieldsBlock() {
        addRow({ type: 'remaining_utility_fields_block', form_section_id: getTargetSectionId(), order: 0 });
    }

    function addRemainingSupplierFieldsBlock() {
        addRow({ type: 'remaining_supplier_fields_block', form_section_id: getTargetSectionId(), order: 0 });
    }

    function removeField(key: string) {
        setFields((prev) => renumberFields(prev.filter((f) => rowKey(f) !== key)));
    }

    function moveFieldToSection(key: string, sectionId: number | null) {
        setFields((prev) => {
            const idx = prev.findIndex((f) => rowKey(f) === key);
            if (idx < 0) return prev;

            const updated = [...prev];
            const [moved] = updated.splice(idx, 1);
            updated.push({ ...moved, form_section_id: sectionId });
            return renumberFields(updated);
        });
    }

    function handleFieldDragStart(key: string) {
        setDraggedFieldKey(key);
        setDraggedSectionId(null);
    }

    function handleFieldDragOver(e: React.DragEvent, key: string) {
        e.preventDefault();
        e.stopPropagation();
        if (key !== draggedFieldKey) {
            setDragOverFieldKey(key);
        }
    }

    function handleFieldDrop(e: React.DragEvent, targetKey: string) {
        e.stopPropagation();
        if (!draggedFieldKey || draggedFieldKey === targetKey) return;

        setFields((prev) => {
            const fromIdx = prev.findIndex((f) => rowKey(f) === draggedFieldKey);
            if (fromIdx < 0) return prev;

            const updated = [...prev];
            const [removed] = updated.splice(fromIdx, 1);
            const toIdx = updated.findIndex((f) => rowKey(f) === targetKey);
            if (toIdx < 0) return prev;

            const target = updated[toIdx];
            updated.splice(toIdx, 0, { ...removed, form_section_id: target.form_section_id });
            return renumberFields(updated);
        });

        setDraggedFieldKey(null);
        setDragOverFieldKey(null);
    }

    function handleGroupDrop(sectionId: number | null) {
        if (!draggedFieldKey) return;

        setFields((prev) => {
            const idx = prev.findIndex((f) => rowKey(f) === draggedFieldKey);
            if (idx < 0) return prev;

            const updated = [...prev];
            const [moved] = updated.splice(idx, 1);
            updated.push({ ...moved, form_section_id: sectionId });
            return renumberFields(updated);
        });

        setDraggedFieldKey(null);
        setDragOverFieldKey(null);
    }

    function handleFieldDragEnd() {
        setDraggedFieldKey(null);
        setDragOverFieldKey(null);
    }

    function addSection(sectionId: number) {
        const section = formSections.find((s) => s.id === sectionId);
        if (!section) return;

        setSections((prev) => [...prev, { ...section, description: null, order: prev.length + 1 }]);
    }

    function removeSection(sectionId: number) {
        setSections((prev) => renumberSections(prev.filter((s) => s.id !== sectionId)));
        setFields((prev) =>
            renumberFields(
                prev.map((f) => (f.form_section_id === sectionId ? { ...f, form_section_id: null } : f)),
            ),
        );
    }

    function handleSectionDragStart(sectionId: number) {
        setDraggedSectionId(sectionId);
        setDraggedFieldKey(null);
    }

    function handleSectionDragOver(e: React.DragEvent, sectionId: number) {
        e.preventDefault();
        if (sectionId !== draggedSectionId) {
            setDragOverSectionId(sectionId);
        }
    }

    function handleSectionDrop(targetSectionId: number) {
        if (draggedSectionId === null || draggedSectionId === targetSectionId) return;

        setSections((prev) => {
            const fromIdx = prev.findIndex((s) => s.id === draggedSectionId);
            const toIdx = prev.findIndex((s) => s.id === targetSectionId);
            if (fromIdx < 0 || toIdx < 0) return prev;

            const updated = [...prev];
            const [removed] = updated.splice(fromIdx, 1);
            updated.splice(toIdx, 0, removed);
            return renumberSections(updated);
        });

        setDraggedSectionId(null);
        setDragOverSectionId(null);
    }

    function handleSectionDragEnd() {
        setDraggedSectionId(null);
        setDragOverSectionId(null);
    }

    function handleSave() {
        if (!selectedFormId) return;

        setSaving(true);
        router.put(
            sync.url(selectedFormId),
            {
                sections: sections.map((s) => ({ id: s.id, order: s.order })),
                fields: fields.map((f) => {
                    const base = { form_section_id: f.form_section_id, order: f.order };
                    if (f.type === 'form_field') return { ...base, id: f.id };
                    if (f.type === 'utility_field') return { ...base, utility_field_name: f.utility_field_name };
                    if (f.type === 'supplier_field') return { ...base, supplier_field_name: f.supplier_field_name };
                    if (f.type === 'affirmations_block') return { ...base, is_affirmations_block: true };
                    if (f.type === 'remaining_utility_fields_block') {
                        return { ...base, is_remaining_utility_fields_block: true };
                    }
                    return { ...base, is_remaining_supplier_fields_block: true };
                }),
            },
            {
                preserveState: true,
                onFinish: () => setSaving(false),
            },
        );
    }

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Head title="Web Form Fields" />

            <h1 className="sr-only">Web Form Fields</h1>

            <div className="space-y-6">
                <HeadingSmall
                    title="Web Form Fields"
                    description="Assign and order form fields and sections within a web form."
                />

                {/* Form selector */}
                <div className="rounded-md border border-zinc-200 bg-white p-4 dark:border-zinc-800 dark:bg-zinc-950">
                    <div className="flex flex-col gap-1 sm:max-w-xs">
                        <label className="text-xs font-medium text-zinc-700 dark:text-zinc-300">
                            Web Form
                        </label>
                        <select
                            className="rounded-md border border-zinc-200 bg-white px-3 py-2 text-sm dark:border-zinc-800 dark:bg-zinc-950"
                            value={selectedFormId ?? ''}
                            onChange={(e) => handleFormChange(e.target.value)}
                        >
                            {webForms.length === 0 && (
                                <option value="" disabled>
                                    No forms available
                                </option>
                            )}
                            {webForms.map((wf) => (
                                <option key={wf.id} value={wf.id}>
                                    {wf.name}
                                </option>
                            ))}
                        </select>
                    </div>
                </div>

                {selectedFormId && (
                    <>
                        {/* Add section to form */}
                        <div className="rounded-md border border-zinc-200 bg-white p-4 dark:border-zinc-800 dark:bg-zinc-950">
                            <p className="mb-3 text-xs font-medium uppercase text-zinc-500 dark:text-zinc-400">
                                Add section to form
                            </p>

                            {formSections.length === 0 ? (
                                <p className="text-sm text-zinc-600 dark:text-zinc-400">
                                    No form sections exist yet. Create one on the{' '}
                                    <a
                                        href={formSectionsIndex.url()}
                                        className="underline hover:text-zinc-900 dark:hover:text-zinc-100"
                                    >
                                        Form Sections
                                    </a>{' '}
                                    page first.
                                </p>
                            ) : availableSections.length === 0 ? (
                                <p className="text-sm text-zinc-600 dark:text-zinc-400">
                                    Every form section is already attached to this form.
                                </p>
                            ) : (
                                <div className="flex items-end gap-3">
                                    <div className="flex flex-col gap-1 sm:min-w-64">
                                        <label className="text-xs font-medium text-zinc-700 dark:text-zinc-300">
                                            Section
                                        </label>
                                        <select
                                            id="add-section-select"
                                            className="rounded-md border border-zinc-200 bg-white px-3 py-2 text-sm dark:border-zinc-800 dark:bg-zinc-950"
                                            defaultValue=""
                                        >
                                            <option value="" disabled>
                                                Select a section...
                                            </option>
                                            {availableSections.map((s) => (
                                                <option key={s.id} value={s.id}>
                                                    {s.label}
                                                </option>
                                            ))}
                                        </select>
                                    </div>
                                    <button
                                        type="button"
                                        onClick={() => {
                                            const select = document.getElementById(
                                                'add-section-select',
                                            ) as HTMLSelectElement;
                                            if (select.value) {
                                                addSection(Number(select.value));
                                                select.value = '';
                                            }
                                        }}
                                        className="rounded-md bg-zinc-900 px-3 py-2 text-sm font-medium text-white disabled:opacity-60 dark:bg-zinc-100 dark:text-zinc-900"
                                    >
                                        Add section
                                    </button>
                                </div>
                            )}
                        </div>

                        {/* Add fields */}
                        <div className="rounded-md border border-zinc-200 bg-white p-4 dark:border-zinc-800 dark:bg-zinc-950 space-y-4">
                            <p className="text-xs font-medium text-zinc-500 uppercase dark:text-zinc-400">
                                Add field to form
                            </p>

                            <div className="flex flex-col gap-1 sm:max-w-xs">
                                <label className="text-xs font-medium text-zinc-700 dark:text-zinc-300">
                                    Target section
                                </label>
                                <select
                                    id="add-target-section-select"
                                    className="rounded-md border border-zinc-200 bg-white px-3 py-2 text-sm dark:border-zinc-800 dark:bg-zinc-950"
                                    defaultValue=""
                                >
                                    <option value="">Unsectioned</option>
                                    {sections.map((s) => (
                                        <option key={s.id} value={s.id}>
                                            {s.label}
                                        </option>
                                    ))}
                                </select>
                                <p className="text-xs text-zinc-500 dark:text-zinc-400">
                                    Applies to everything added below. Fields can be moved between
                                    sections afterward.
                                </p>
                            </div>

                            <div className="flex items-end gap-3 border-t border-zinc-100 pt-4 dark:border-zinc-800">
                                <div className="flex flex-col gap-1 sm:min-w-64">
                                    <label className="text-xs font-medium text-zinc-700 dark:text-zinc-300">
                                        Form Field
                                    </label>
                                    <select
                                        id="add-field-select"
                                        className="rounded-md border border-zinc-200 bg-white px-3 py-2 text-sm dark:border-zinc-800 dark:bg-zinc-950"
                                        defaultValue=""
                                    >
                                        <option value="" disabled>
                                            Select a field...
                                        </option>
                                        {availableFormFields.map((f) => (
                                            <option key={f.id} value={f.id}>
                                                {f.name} — {f.label}
                                            </option>
                                        ))}
                                    </select>
                                </div>
                                <button
                                    type="button"
                                    onClick={() => {
                                        const select = document.getElementById(
                                            'add-field-select',
                                        ) as HTMLSelectElement;
                                        if (select.value) {
                                            addFormField(Number(select.value));
                                            select.value = '';
                                        }
                                    }}
                                    className="rounded-md bg-zinc-900 px-3 py-2 text-sm font-medium text-white disabled:opacity-60 dark:bg-zinc-100 dark:text-zinc-900"
                                >
                                    Add
                                </button>
                            </div>

                            {availableUtilityFields.length > 0 && (
                                <div className="flex items-end gap-3 border-t border-zinc-100 pt-4 dark:border-zinc-800">
                                    <div className="flex flex-col gap-1 sm:min-w-64">
                                        <label className="text-xs font-medium text-zinc-700 dark:text-zinc-300">
                                            Utility Field Slot
                                        </label>
                                        <select
                                            id="add-utility-select"
                                            className="rounded-md border border-zinc-200 bg-white px-3 py-2 text-sm dark:border-zinc-800 dark:bg-zinc-950"
                                            defaultValue=""
                                        >
                                            <option value="" disabled>
                                                Select a utility field...
                                            </option>
                                            {availableUtilityFields.map((uf) => (
                                                <option key={uf.value} value={uf.value}>
                                                    {uf.label}
                                                </option>
                                            ))}
                                        </select>
                                    </div>
                                    <button
                                        type="button"
                                        onClick={() => {
                                            const select = document.getElementById(
                                                'add-utility-select',
                                            ) as HTMLSelectElement;
                                            if (select.value) {
                                                addUtilityField(select.value);
                                                select.value = '';
                                            }
                                        }}
                                        className="rounded-md bg-zinc-900 px-3 py-2 text-sm font-medium text-white disabled:opacity-60 dark:bg-zinc-100 dark:text-zinc-900"
                                    >
                                        Add slot
                                    </button>
                                </div>
                            )}

                            <div className="flex items-end gap-3 border-t border-zinc-100 pt-4 dark:border-zinc-800">
                                <div className="flex flex-col gap-1 sm:min-w-64">
                                    <label className="text-xs font-medium text-zinc-700 dark:text-zinc-300">
                                        Supplier Field Slot
                                    </label>
                                    <input
                                        id="add-supplier-field-input"
                                        className="rounded-md border border-zinc-200 bg-white px-3 py-2 text-sm dark:border-zinc-800 dark:bg-zinc-950"
                                        placeholder="e.g. birth_date"
                                    />
                                </div>
                                <button
                                    type="button"
                                    onClick={() => {
                                        const input = document.getElementById(
                                            'add-supplier-field-input',
                                        ) as HTMLInputElement;
                                        const name = input.value.trim();
                                        if (name && !assignedSupplierFieldNames.includes(name)) {
                                            addSupplierField(name);
                                            input.value = '';
                                        }
                                    }}
                                    className="rounded-md bg-zinc-900 px-3 py-2 text-sm font-medium text-white disabled:opacity-60 dark:bg-zinc-100 dark:text-zinc-900"
                                >
                                    Add slot
                                </button>
                            </div>

                            {!hasAffirmationsBlock && (
                                <div className="flex items-center gap-3 border-t border-zinc-100 pt-4 dark:border-zinc-800">
                                    <div className="flex flex-col gap-1">
                                        <p className="text-xs font-medium text-zinc-700 dark:text-zinc-300">
                                            Affirmations Block
                                        </p>
                                        <p className="text-xs text-zinc-500 dark:text-zinc-400">
                                            Marks where supplier/state affirmations appear in the form. If omitted, they are appended to the unsectioned group.
                                        </p>
                                    </div>
                                    <button
                                        type="button"
                                        onClick={addAffirmationsBlock}
                                        className="shrink-0 rounded-md bg-zinc-900 px-3 py-2 text-sm font-medium text-white disabled:opacity-60 dark:bg-zinc-100 dark:text-zinc-900"
                                    >
                                        Add block
                                    </button>
                                </div>
                            )}

                            {!hasRemainingUtilityFieldsBlock && (
                                <div className="flex items-center gap-3 border-t border-zinc-100 pt-4 dark:border-zinc-800">
                                    <div className="flex flex-col gap-1">
                                        <p className="text-xs font-medium text-zinc-700 dark:text-zinc-300">
                                            Remaining Utility Fields Block
                                        </p>
                                        <p className="text-xs text-zinc-500 dark:text-zinc-400">
                                            Expands to every utility field not placed explicitly. If omitted, they are appended to the unsectioned group.
                                        </p>
                                    </div>
                                    <button
                                        type="button"
                                        onClick={addRemainingUtilityFieldsBlock}
                                        className="shrink-0 rounded-md bg-zinc-900 px-3 py-2 text-sm font-medium text-white disabled:opacity-60 dark:bg-zinc-100 dark:text-zinc-900"
                                    >
                                        Add block
                                    </button>
                                </div>
                            )}

                            {!hasRemainingSupplierFieldsBlock && (
                                <div className="flex items-center gap-3 border-t border-zinc-100 pt-4 dark:border-zinc-800">
                                    <div className="flex flex-col gap-1">
                                        <p className="text-xs font-medium text-zinc-700 dark:text-zinc-300">
                                            Remaining Supplier Fields Block
                                        </p>
                                        <p className="text-xs text-zinc-500 dark:text-zinc-400">
                                            Expands to every supplier field not placed explicitly. If omitted, they are appended to the unsectioned group.
                                        </p>
                                    </div>
                                    <button
                                        type="button"
                                        onClick={addRemainingSupplierFieldsBlock}
                                        className="shrink-0 rounded-md bg-zinc-900 px-3 py-2 text-sm font-medium text-white disabled:opacity-60 dark:bg-zinc-100 dark:text-zinc-900"
                                    >
                                        Add block
                                    </button>
                                </div>
                            )}
                        </div>

                        {/* Section cards */}
                        <div className="space-y-4">
                            {groups.map((group) => {
                                const groupKey = group.id === null ? 'unsectioned' : `section_${group.id}`;
                                const rows = groupFields(group.id);
                                const isDraggedOverSection =
                                    group.id !== null && dragOverSectionId === group.id;

                                return (
                                    <div
                                        key={groupKey}
                                        className={[
                                            'overflow-hidden rounded-md border border-zinc-200 bg-white dark:border-zinc-800 dark:bg-zinc-950',
                                            isDraggedOverSection
                                                ? 'outline outline-2 outline-zinc-400 dark:outline-zinc-500'
                                                : '',
                                        ]
                                            .filter(Boolean)
                                            .join(' ')}
                                    >
                                        {group.id === null ? (
                                            <div className="flex items-center justify-between border-b border-zinc-200 bg-zinc-50 px-4 py-3 dark:border-zinc-800 dark:bg-zinc-900">
                                                <div>
                                                    <p className="text-sm font-medium text-zinc-900 dark:text-zinc-100">
                                                        Unsectioned
                                                    </p>
                                                    <p className="text-xs text-zinc-500 dark:text-zinc-400">
                                                        Fields not assigned to a section. Returned first in the API.
                                                    </p>
                                                </div>
                                            </div>
                                        ) : (
                                            <div
                                                draggable
                                                onDragStart={() => handleSectionDragStart(group.id as number)}
                                                onDragOver={(e) => handleSectionDragOver(e, group.id as number)}
                                                onDrop={() => handleSectionDrop(group.id as number)}
                                                onDragEnd={handleSectionDragEnd}
                                                className="flex cursor-grab items-center justify-between border-b border-zinc-200 bg-zinc-50 px-4 py-3 active:cursor-grabbing dark:border-zinc-800 dark:bg-zinc-900"
                                            >
                                                <div className="flex items-center gap-2">
                                                    <GripVertical className="size-4 text-zinc-400 dark:text-zinc-600" />
                                                    <p className="text-sm font-medium text-zinc-900 dark:text-zinc-100">
                                                        {group.label}
                                                    </p>
                                                    <span className="font-mono text-xs text-zinc-500 dark:text-zinc-400">
                                                        {group.name}
                                                    </span>
                                                </div>
                                                <button
                                                    type="button"
                                                    onClick={() => removeSection(group.id as number)}
                                                    className="text-sm text-red-700 hover:underline dark:text-red-400"
                                                >
                                                    Remove from form
                                                </button>
                                            </div>
                                        )}

                                        <div
                                            onDragOver={(e) => {
                                                if (draggedFieldKey) e.preventDefault();
                                            }}
                                            onDrop={() => handleGroupDrop(group.id)}
                                        >
                                            {rows.length > 0 ? (
                                                <div className="overflow-x-auto">
                                                    <table className="w-full text-left text-sm">
                                                        <thead className="border-b border-zinc-200 text-xs text-zinc-600 uppercase dark:border-zinc-800 dark:text-zinc-400">
                                                            <tr>
                                                                <th className="w-8 px-2 py-3" />
                                                                <th className="px-4 py-3">Name</th>
                                                                <th className="px-4 py-3">Label / Field</th>
                                                                <th className="px-4 py-3">Section</th>
                                                                <th className="px-4 py-3" />
                                                            </tr>
                                                        </thead>
                                                        <tbody className="divide-y divide-zinc-200 dark:divide-zinc-800">
                                                            {rows.map((f) => {
                                                                const key = rowKey(f);
                                                                const isUtility = f.type === 'utility_field';
                                                                const isSupplier = f.type === 'supplier_field';
                                                                const isAffirmationsBlock = f.type === 'affirmations_block';
                                                                const isRemainingUtilityBlock =
                                                                    f.type === 'remaining_utility_fields_block';
                                                                const isRemainingSupplierBlock =
                                                                    f.type === 'remaining_supplier_fields_block';
                                                                const isDragging = draggedFieldKey === key;
                                                                const isDragOver = dragOverFieldKey === key;
                                                                return (
                                                                    <tr
                                                                        key={key}
                                                                        draggable
                                                                        onDragStart={() => handleFieldDragStart(key)}
                                                                        onDragOver={(e) => handleFieldDragOver(e, key)}
                                                                        onDrop={(e) => handleFieldDrop(e, key)}
                                                                        onDragEnd={handleFieldDragEnd}
                                                                        className={[
                                                                            'transition-opacity',
                                                                            isDragging ? 'opacity-40' : '',
                                                                            isDragOver
                                                                                ? 'outline outline-2 outline-zinc-400 dark:outline-zinc-500'
                                                                                : '',
                                                                            isUtility ? 'bg-blue-50 dark:bg-blue-950/20' : '',
                                                                            isSupplier ? 'bg-amber-50 dark:bg-amber-950/20' : '',
                                                                            isAffirmationsBlock ? 'bg-violet-50 dark:bg-violet-950/20' : '',
                                                                            isRemainingUtilityBlock ? 'bg-teal-50 dark:bg-teal-950/20' : '',
                                                                            isRemainingSupplierBlock ? 'bg-rose-50 dark:bg-rose-950/20' : '',
                                                                        ]
                                                                            .filter(Boolean)
                                                                            .join(' ')}
                                                                    >
                                                                        <td className="w-8 px-2 py-3 text-zinc-400 dark:text-zinc-600">
                                                                            <GripVertical className="size-4 cursor-grab active:cursor-grabbing" />
                                                                        </td>
                                                                        <td className="px-4 py-3 font-mono text-xs">
                                                                            {isUtility ? (
                                                                                <span className="text-blue-700 dark:text-blue-400">
                                                                                    {f.utility_field_name}
                                                                                </span>
                                                                            ) : isSupplier ? (
                                                                                <span className="text-amber-700 dark:text-amber-400">
                                                                                    {f.supplier_field_name}
                                                                                </span>
                                                                            ) : isAffirmationsBlock ? (
                                                                                <span className="text-violet-700 dark:text-violet-400">
                                                                                    affirmations
                                                                                </span>
                                                                            ) : isRemainingUtilityBlock ? (
                                                                                <span className="text-teal-700 dark:text-teal-400">
                                                                                    remaining utility fields
                                                                                </span>
                                                                            ) : isRemainingSupplierBlock ? (
                                                                                <span className="text-rose-700 dark:text-rose-400">
                                                                                    remaining supplier fields
                                                                                </span>
                                                                            ) : (
                                                                                f.name
                                                                            )}
                                                                        </td>
                                                                        <td className="px-4 py-3">
                                                                            {isUtility ? (
                                                                                <span className="inline-flex items-center rounded-full bg-blue-100 px-2 py-0.5 text-xs font-medium text-blue-700 dark:bg-blue-900 dark:text-blue-300">
                                                                                    utility field slot
                                                                                </span>
                                                                            ) : isSupplier ? (
                                                                                <span className="inline-flex items-center rounded-full bg-amber-100 px-2 py-0.5 text-xs font-medium text-amber-700 dark:bg-amber-900 dark:text-amber-300">
                                                                                    supplier field slot
                                                                                </span>
                                                                            ) : isAffirmationsBlock ? (
                                                                                <span className="inline-flex items-center rounded-full bg-violet-100 px-2 py-0.5 text-xs font-medium text-violet-700 dark:bg-violet-900 dark:text-violet-300">
                                                                                    affirmations block
                                                                                </span>
                                                                            ) : isRemainingUtilityBlock ? (
                                                                                <span className="inline-flex items-center rounded-full bg-teal-100 px-2 py-0.5 text-xs font-medium text-teal-700 dark:bg-teal-900 dark:text-teal-300">
                                                                                    remaining utility fields block
                                                                                </span>
                                                                            ) : isRemainingSupplierBlock ? (
                                                                                <span className="inline-flex items-center rounded-full bg-rose-100 px-2 py-0.5 text-xs font-medium text-rose-700 dark:bg-rose-900 dark:text-rose-300">
                                                                                    remaining supplier fields block
                                                                                </span>
                                                                            ) : (
                                                                                f.label
                                                                            )}
                                                                        </td>
                                                                        <td className="px-4 py-3">
                                                                            <select
                                                                                value={f.form_section_id ?? ''}
                                                                                onChange={(e) =>
                                                                                    moveFieldToSection(
                                                                                        key,
                                                                                        e.target.value
                                                                                            ? Number(e.target.value)
                                                                                            : null,
                                                                                    )
                                                                                }
                                                                                className="rounded-md border border-zinc-200 bg-white px-2 py-1 text-xs dark:border-zinc-800 dark:bg-zinc-950"
                                                                            >
                                                                                <option value="">Unsectioned</option>
                                                                                {sections.map((s) => (
                                                                                    <option key={s.id} value={s.id}>
                                                                                        {s.label}
                                                                                    </option>
                                                                                ))}
                                                                            </select>
                                                                        </td>
                                                                        <td className="px-4 py-3 text-right">
                                                                            <button
                                                                                type="button"
                                                                                onClick={() => removeField(key)}
                                                                                className="text-sm text-red-700 hover:underline dark:text-red-400"
                                                                            >
                                                                                Remove
                                                                            </button>
                                                                        </td>
                                                                    </tr>
                                                                );
                                                            })}
                                                        </tbody>
                                                    </table>
                                                </div>
                                            ) : (
                                                <div className="m-4 rounded-md border-2 border-dashed border-zinc-200 p-4 text-center text-sm text-zinc-500 dark:border-zinc-800 dark:text-zinc-400">
                                                    Drop fields here
                                                </div>
                                            )}
                                        </div>
                                    </div>
                                );
                            })}
                        </div>

                        {/* Save button */}
                        <div>
                            <button
                                type="button"
                                disabled={saving}
                                onClick={handleSave}
                                className="rounded-md bg-zinc-900 px-3 py-2 text-sm font-medium text-white disabled:opacity-60 dark:bg-zinc-100 dark:text-zinc-900"
                            >
                                Save field assignments
                            </button>
                        </div>
                    </>
                )}
            </div>
        </AppLayout>
    );
}
