import { Form, Head } from '@inertiajs/react';
import { useState } from 'react';

import HeadingSmall from '@/components/heading-small';
import { SortableHeader, useSort } from '@/components/sortable-header';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogHeader,
    DialogTitle,
    DialogTrigger,
} from '@/components/ui/dialog';
import AppLayout from '@/layouts/app-layout';
import { destroy, index, store, update } from '@/routes/admin/form-sections';

type FormSection = {
    id: number;
    name: string;
    label: string;
    description: string | null;
    form_form_fields_count: number;
    web_forms_count: number;
};

type Props = {
    formSections: FormSection[];
};

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

export default function FormSections({ formSections }: Props) {
    const [createOpen, setCreateOpen] = useState(false);
    const [editingId, setEditingId] = useState<number | null>(null);
    const { sorted, sortColumn, sortDirection, toggleSort } = useSort<FormSection>(formSections, 'name');

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

            <h1 className="sr-only">Form Sections</h1>

            <div className="space-y-6">
                <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
                    <HeadingSmall
                        title="Form Sections"
                        description="Manage the reusable sections form fields can be grouped into."
                    />

                    <Dialog open={createOpen} onOpenChange={setCreateOpen}>
                        <DialogTrigger asChild>
                            <button
                                type="button"
                                className="rounded-md bg-zinc-900 px-3 py-2 text-sm font-medium text-white dark:bg-zinc-100 dark:text-zinc-900"
                            >
                                Add form section
                            </button>
                        </DialogTrigger>

                        <DialogContent className="sm:max-w-lg">
                            <DialogHeader>
                                <DialogTitle>Add form section</DialogTitle>
                                <DialogDescription>
                                    Create a new section that form fields can be grouped into.
                                </DialogDescription>
                            </DialogHeader>

                            <Form
                                method="post"
                                action={store.url()}
                                resetOnSuccess
                                onSuccess={() => setCreateOpen(false)}
                            >
                                {({ processing, errors }) => (
                                    <div className="grid grid-cols-1 gap-3">
                                        <div className="flex flex-col gap-1">
                                            <label className="text-xs font-medium text-zinc-700 dark:text-zinc-300">
                                                Name
                                            </label>
                                            <input
                                                name="name"
                                                className="rounded-md border border-zinc-200 bg-white px-3 py-2 text-sm dark:border-zinc-800 dark:bg-zinc-950"
                                                placeholder="contact_information"
                                            />
                                            {errors.name && (
                                                <div className="text-xs text-red-600">{errors.name}</div>
                                            )}
                                        </div>

                                        <div className="flex flex-col gap-1">
                                            <label className="text-xs font-medium text-zinc-700 dark:text-zinc-300">
                                                Label
                                            </label>
                                            <input
                                                name="label"
                                                className="rounded-md border border-zinc-200 bg-white px-3 py-2 text-sm dark:border-zinc-800 dark:bg-zinc-950"
                                                placeholder="Contact Information"
                                            />
                                            {errors.label && (
                                                <div className="text-xs text-red-600">{errors.label}</div>
                                            )}
                                        </div>

                                        <div className="flex flex-col gap-1">
                                            <label className="text-xs font-medium text-zinc-700 dark:text-zinc-300">
                                                Description
                                            </label>
                                            <textarea
                                                name="description"
                                                rows={3}
                                                className="resize-y rounded-md border border-zinc-200 bg-white px-3 py-2 text-sm dark:border-zinc-800 dark:bg-zinc-950"
                                                placeholder="Optional text shown above the section"
                                            />
                                            {errors.description && (
                                                <div className="text-xs text-red-600">{errors.description}</div>
                                            )}
                                        </div>

                                        <div className="flex items-end justify-end gap-3">
                                            <button
                                                type="button"
                                                onClick={() => setCreateOpen(false)}
                                                className="rounded-md px-3 py-2 text-sm font-medium text-zinc-600 hover:text-zinc-900 dark:text-zinc-400 dark:hover:text-zinc-100"
                                            >
                                                Cancel
                                            </button>
                                            <button
                                                type="submit"
                                                disabled={processing}
                                                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 form section
                                            </button>
                                        </div>
                                    </div>
                                )}
                            </Form>
                        </DialogContent>
                    </Dialog>
                </div>

                {/* Form sections table */}
                <div className="overflow-hidden rounded-md border border-zinc-200 bg-white dark:border-zinc-800 dark:bg-zinc-950">
                    <div className="overflow-x-auto">
                        <table className="w-full text-left text-sm">
                            <thead className="border-b border-zinc-200 text-xs uppercase text-zinc-600 dark:border-zinc-800 dark:text-zinc-400">
                                <tr>
                                    <SortableHeader label="Name" column="name" sortColumn={sortColumn} sortDirection={sortDirection} onSort={toggleSort} />
                                    <SortableHeader label="Label" column="label" sortColumn={sortColumn} sortDirection={sortDirection} onSort={toggleSort} />
                                    <th className="px-4 py-3">Description</th>
                                    <th className="px-4 py-3">Used by</th>
                                    <th className="px-4 py-3" />
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-zinc-200 dark:divide-zinc-800">
                                {sorted.map((s) => (
                                    <tr key={s.id}>
                                        <td className="px-4 py-3 font-mono text-xs font-medium">
                                            {s.name}
                                        </td>
                                        <td className="px-4 py-3">{s.label}</td>
                                        <td className="px-4 py-3 text-zinc-600 dark:text-zinc-400">
                                            {s.description ?? '—'}
                                        </td>
                                        <td className="px-4 py-3 text-zinc-600 dark:text-zinc-400">
                                            {s.form_form_fields_count} field{s.form_form_fields_count === 1 ? '' : 's'},{' '}
                                            {s.web_forms_count} form{s.web_forms_count === 1 ? '' : 's'}
                                        </td>
                                        <td className="px-4 py-3 text-right">
                                            <div className="flex items-center justify-end gap-4">
                                                <Dialog
                                                    open={editingId === s.id}
                                                    onOpenChange={(open) => setEditingId(open ? s.id : null)}
                                                >
                                                    <DialogTrigger asChild>
                                                        <button
                                                            type="button"
                                                            className="text-sm text-zinc-700 hover:underline dark:text-zinc-300"
                                                        >
                                                            Edit
                                                        </button>
                                                    </DialogTrigger>

                                                    <DialogContent className="sm:max-w-lg">
                                                        <DialogHeader>
                                                            <DialogTitle>Edit form section</DialogTitle>
                                                            <DialogDescription>
                                                                Update {s.name} settings.
                                                            </DialogDescription>
                                                        </DialogHeader>

                                                        <Form
                                                            method="put"
                                                            action={update.url(s.id)}
                                                            onSuccess={() => setEditingId(null)}
                                                        >
                                                            {({ processing, errors }) => (
                                                                <div className="grid grid-cols-1 gap-3">
                                                                    <div className="flex flex-col gap-1">
                                                                        <label className="text-xs font-medium text-zinc-700 dark:text-zinc-300">
                                                                            Name
                                                                        </label>
                                                                        <input
                                                                            name="name"
                                                                            defaultValue={s.name}
                                                                            className="rounded-md border border-zinc-200 bg-white px-3 py-2 text-sm dark:border-zinc-800 dark:bg-zinc-950"
                                                                        />
                                                                        {errors.name && (
                                                                            <div className="text-xs text-red-600">
                                                                                {errors.name}
                                                                            </div>
                                                                        )}
                                                                    </div>

                                                                    <div className="flex flex-col gap-1">
                                                                        <label className="text-xs font-medium text-zinc-700 dark:text-zinc-300">
                                                                            Label
                                                                        </label>
                                                                        <input
                                                                            name="label"
                                                                            defaultValue={s.label}
                                                                            className="rounded-md border border-zinc-200 bg-white px-3 py-2 text-sm dark:border-zinc-800 dark:bg-zinc-950"
                                                                        />
                                                                        {errors.label && (
                                                                            <div className="text-xs text-red-600">
                                                                                {errors.label}
                                                                            </div>
                                                                        )}
                                                                    </div>

                                                                    <div className="flex flex-col gap-1">
                                                                        <label className="text-xs font-medium text-zinc-700 dark:text-zinc-300">
                                                                            Description
                                                                        </label>
                                                                        <textarea
                                                                            name="description"
                                                                            defaultValue={s.description ?? ''}
                                                                            rows={3}
                                                                            className="resize-y rounded-md border border-zinc-200 bg-white px-3 py-2 text-sm dark:border-zinc-800 dark:bg-zinc-950"
                                                                        />
                                                                        {errors.description && (
                                                                            <div className="text-xs text-red-600">
                                                                                {errors.description}
                                                                            </div>
                                                                        )}
                                                                    </div>

                                                                    {s.form_form_fields_count > 0 && (
                                                                        <p className="text-xs text-amber-700 dark:text-amber-400">
                                                                            Used by {s.form_form_fields_count} field
                                                                            {s.form_form_fields_count === 1 ? '' : 's'} across{' '}
                                                                            {s.web_forms_count} form
                                                                            {s.web_forms_count === 1 ? '' : 's'}. Changes to
                                                                            the label apply everywhere it&apos;s used.
                                                                        </p>
                                                                    )}

                                                                    <div className="flex items-end justify-end gap-3">
                                                                        <button
                                                                            type="button"
                                                                            onClick={() => setEditingId(null)}
                                                                            className="rounded-md px-3 py-2 text-sm font-medium text-zinc-600 hover:text-zinc-900 dark:text-zinc-400 dark:hover:text-zinc-100"
                                                                        >
                                                                            Cancel
                                                                        </button>
                                                                        <button
                                                                            type="submit"
                                                                            disabled={processing}
                                                                            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
                                                                        </button>
                                                                    </div>
                                                                </div>
                                                            )}
                                                        </Form>
                                                    </DialogContent>
                                                </Dialog>

                                                <Form
                                                    method="delete"
                                                    action={destroy.url(s.id)}
                                                    onBefore={() =>
                                                        s.form_form_fields_count === 0 ||
                                                        window.confirm(
                                                            `${s.form_form_fields_count} field(s) using "${s.label}" will become unsectioned. Delete anyway?`,
                                                        )
                                                    }
                                                >
                                                    {({ processing }) => (
                                                        <button
                                                            type="submit"
                                                            disabled={processing}
                                                            className="text-sm text-red-700 hover:underline disabled:opacity-60 dark:text-red-400"
                                                        >
                                                            Delete
                                                        </button>
                                                    )}
                                                </Form>
                                            </div>
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>

                    {formSections.length === 0 && (
                        <div className="p-4 text-sm text-zinc-600 dark:text-zinc-400">
                            No form sections yet.
                        </div>
                    )}
                </div>
            </div>
        </AppLayout>
    );
}
