import { Form, Head } from '@inertiajs/react';
import { Check, Copy } from 'lucide-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/web-forms';

const FORM_TYPES = [
    { value: 'enrollment', label: 'Enrollment' },
    { value: 'credit_check', label: 'Credit Check' },
] as const;

type FormTypeValue = (typeof FORM_TYPES)[number]['value'];

type WebForm = {
    id: number;
    name: string;
    slug: string;
    type: FormTypeValue;
    description: string | null;
    post_path: string | null;
};

type Props = {
    webForms: WebForm[];
};

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

function CopyButton({ text }: { text: string }) {
    const [copied, setCopied] = useState(false);

    function copy() {
        navigator.clipboard.writeText(text).then(() => {
            setCopied(true);
            setTimeout(() => setCopied(false), 2000);
        });
    }

    return (
        <button
            type="button"
            onClick={copy}
            className="ml-1 inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-xs text-zinc-500 hover:bg-zinc-100 hover:text-zinc-800 dark:hover:bg-zinc-800 dark:hover:text-zinc-200"
        >
            {copied ? <Check className="size-3" /> : <Copy className="size-3" />}
        </button>
    );
}

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

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

            <h1 className="sr-only">Web Forms</h1>

            <div className="space-y-6">
                <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
                    <HeadingSmall
                        title="Web Forms"
                        description="Manage web forms and their configurations."
                    />

                    <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 web form
                            </button>
                        </DialogTrigger>

                        <DialogContent className="sm:max-w-lg">
                            <DialogHeader>
                                <DialogTitle>Add web form</DialogTitle>
                                <DialogDescription>
                                    Create a new web form and configure its settings.
                                </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="Enrollment Form"
                                            />
                                            {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">
                                                Slug{' '}
                                                <span className="font-normal text-zinc-400">
                                                    (auto-generated if blank)
                                                </span>
                                            </label>
                                            <input
                                                name="slug"
                                                className="rounded-md border border-zinc-200 bg-white px-3 py-2 text-sm dark:border-zinc-800 dark:bg-zinc-950"
                                                placeholder="enrollment-form"
                                            />
                                            {errors.slug && (
                                                <div className="text-xs text-red-600">{errors.slug}</div>
                                            )}
                                        </div>

                                        <div className="flex flex-col gap-1">
                                            <label className="text-xs font-medium text-zinc-700 dark:text-zinc-300">
                                                Type
                                            </label>
                                            <select
                                                name="type"
                                                defaultValue="enrollment"
                                                className="rounded-md border border-zinc-200 bg-white px-3 py-2 text-sm dark:border-zinc-800 dark:bg-zinc-950"
                                            >
                                                {FORM_TYPES.map((t) => (
                                                    <option key={t.value} value={t.value}>
                                                        {t.label}
                                                    </option>
                                                ))}
                                            </select>
                                            {errors.type && (
                                                <div className="text-xs text-red-600">{errors.type}</div>
                                            )}
                                        </div>

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

                                        <div className="flex flex-col gap-1">
                                            <label className="text-xs font-medium text-zinc-700 dark:text-zinc-300">
                                                Post path
                                            </label>
                                            <input
                                                name="post_path"
                                                className="rounded-md border border-zinc-200 bg-white px-3 py-2 text-sm dark:border-zinc-800 dark:bg-zinc-950"
                                                placeholder="/api/public/v1/enrollment-requests"
                                            />
                                            {errors.post_path && (
                                                <div className="text-xs text-red-600">{errors.post_path}</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 web form
                                            </button>
                                        </div>
                                    </div>
                                )}
                            </Form>
                        </DialogContent>
                    </Dialog>
                </div>

                {/* Web forms 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="Type"
                                        column="type"
                                        sortColumn={sortColumn}
                                        sortDirection={sortDirection}
                                        onSort={toggleSort}
                                    />
                                    <SortableHeader
                                        label="Description"
                                        column="description"
                                        sortColumn={sortColumn}
                                        sortDirection={sortDirection}
                                        onSort={toggleSort}
                                    />
                                    <th className="px-4 py-3 text-xs font-medium uppercase text-zinc-600 dark:text-zinc-400">
                                        Form API URL
                                    </th>
                                    <th className="px-4 py-3" />
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-zinc-200 dark:divide-zinc-800">
                                {sorted.map((wf) => {
                                    const apiUrl = `${window.location.origin}/api/public/v1/web-forms/${wf.slug}`;
                                    return (
                                    <tr key={wf.id}>
                                        <td className="px-4 py-3 font-medium">{wf.name}</td>
                                        <td className="px-4 py-3 text-zinc-600 dark:text-zinc-400">
                                            {FORM_TYPES.find((t) => t.value === wf.type)?.label ?? wf.type}
                                        </td>
                                        <td className="px-4 py-3 text-zinc-600 dark:text-zinc-400">
                                            {wf.description ?? '—'}
                                        </td>
                                        <td className="px-4 py-3">
                                            <div className="flex items-center gap-1">
                                                <code className="rounded bg-zinc-100 px-1.5 py-0.5 text-xs text-zinc-700 dark:bg-zinc-800 dark:text-zinc-300">
                                                    {apiUrl}
                                                </code>
                                                <CopyButton text={apiUrl} />
                                            </div>
                                        </td>
                                        <td className="px-4 py-3 text-right">
                                            <div className="flex items-center justify-end gap-4">
                                                <Dialog
                                                    open={editingId === wf.id}
                                                    onOpenChange={(open) => setEditingId(open ? wf.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 web form</DialogTitle>
                                                            <DialogDescription>
                                                                Update {wf.name} settings.
                                                            </DialogDescription>
                                                        </DialogHeader>

                                                        <Form
                                                            method="put"
                                                            action={update.url(wf.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={wf.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">
                                                                            Slug
                                                                        </label>
                                                                        <input
                                                                            name="slug"
                                                                            defaultValue={wf.slug}
                                                                            className="rounded-md border border-zinc-200 bg-white px-3 py-2 text-sm dark:border-zinc-800 dark:bg-zinc-950"
                                                                        />
                                                                        {errors.slug && (
                                                                            <div className="text-xs text-red-600">
                                                                                {errors.slug}
                                                                            </div>
                                                                        )}
                                                                    </div>

                                                                    <div className="flex flex-col gap-1">
                                                                        <label className="text-xs font-medium text-zinc-700 dark:text-zinc-300">
                                                                            Type
                                                                        </label>
                                                                        <select
                                                                            name="type"
                                                                            defaultValue={wf.type}
                                                                            className="rounded-md border border-zinc-200 bg-white px-3 py-2 text-sm dark:border-zinc-800 dark:bg-zinc-950"
                                                                        >
                                                                            {FORM_TYPES.map((t) => (
                                                                                <option key={t.value} value={t.value}>
                                                                                    {t.label}
                                                                                </option>
                                                                            ))}
                                                                        </select>
                                                                        {errors.type && (
                                                                            <div className="text-xs text-red-600">
                                                                                {errors.type}
                                                                            </div>
                                                                        )}
                                                                    </div>

                                                                    <div className="flex flex-col gap-1">
                                                                        <label className="text-xs font-medium text-zinc-700 dark:text-zinc-300">
                                                                            Description
                                                                        </label>
                                                                        <input
                                                                            name="description"
                                                                            defaultValue={wf.description ?? ''}
                                                                            className="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>

                                                                    <div className="flex flex-col gap-1">
                                                                        <label className="text-xs font-medium text-zinc-700 dark:text-zinc-300">
                                                                            Post path
                                                                        </label>
                                                                        <input
                                                                            name="post_path"
                                                                            defaultValue={wf.post_path ?? ''}
                                                                            className="rounded-md border border-zinc-200 bg-white px-3 py-2 text-sm dark:border-zinc-800 dark:bg-zinc-950"
                                                                            placeholder="/api/public/v1/enrollment-requests"
                                                                        />
                                                                        {errors.post_path && (
                                                                            <div className="text-xs text-red-600">
                                                                                {errors.post_path}
                                                                            </div>
                                                                        )}
                                                                    </div>

                                                                    <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(wf.id)}>
                                                    {({ 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>

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