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

import HeadingSmall from '@/components/heading-small';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogHeader,
    DialogTitle,
    DialogTrigger,
} from '@/components/ui/dialog';
import AppLayout from '@/layouts/app-layout';
import { index as integrationsIndex } from '@/routes/admin/integrations';
import { index, store, update, destroy } from '@/routes/admin/integrations/settings';

type Integration = {
    id: number;
    key: string;
    name: string;
};

type IntegrationSetting = {
    id: number;
    key: string;
    value: string | null;
};

type Props = {
    integration: Integration;
    settings: IntegrationSetting[];
};

export default function IntegrationSettings({ integration, settings }: Props) {
    const [editingId, setEditingId] = useState<number | null>(null);
    const [createOpen, setCreateOpen] = useState(false);

    const breadcrumbs = [
        { title: 'Integrations', href: integrationsIndex.url() },
        { title: integration.name, href: index.url(integration.id) },
    ];

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Head title={`${integration.name} Settings`} />

            <h1 className="sr-only">{integration.name} Settings</h1>

            <div className="space-y-6">
                <div className="flex items-center justify-between">
                    <div className="space-y-1">
                        <Link
                            href={integrationsIndex.url()}
                            className="text-xs text-zinc-500 hover:underline dark:text-zinc-400"
                        >
                            &larr; Back to integrations
                        </Link>
                        <HeadingSmall
                            title={`${integration.name} Settings`}
                            description="Key-value configuration used by this integration, editable without a deploy."
                        />
                    </div>

                    <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 setting
                            </button>
                        </DialogTrigger>

                        <DialogContent className="sm:max-w-md">
                            <DialogHeader>
                                <DialogTitle>Add setting</DialogTitle>
                                <DialogDescription>
                                    Add a new key-value setting for {integration.name}.
                                </DialogDescription>
                            </DialogHeader>

                            <Form
                                method="post"
                                action={store.url(integration.id)}
                                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">
                                                Key
                                            </label>
                                            <input
                                                name="key"
                                                className="rounded-md border border-zinc-200 bg-white px-3 py-2 text-sm font-mono dark:border-zinc-800 dark:bg-zinc-950"
                                                placeholder="spreadsheet_id"
                                            />
                                            {errors.key && (
                                                <div className="text-xs text-red-600">{errors.key}</div>
                                            )}
                                        </div>

                                        <div className="flex flex-col gap-1">
                                            <label className="text-xs font-medium text-zinc-700 dark:text-zinc-300">
                                                Value
                                            </label>
                                            <input
                                                name="value"
                                                className="rounded-md border border-zinc-200 bg-white px-3 py-2 text-sm dark:border-zinc-800 dark:bg-zinc-950"
                                            />
                                            {errors.value && (
                                                <div className="text-xs text-red-600">{errors.value}</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 setting
                                            </button>
                                        </div>
                                    </div>
                                )}
                            </Form>
                        </DialogContent>
                    </Dialog>
                </div>

                <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>
                                    <th className="px-4 py-3">Key</th>
                                    <th className="px-4 py-3">Value</th>
                                    <th className="px-4 py-3" />
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-zinc-200 dark:divide-zinc-800">
                                {settings.map((setting) => (
                                    <tr key={setting.id}>
                                        <td className="px-4 py-3 font-mono text-xs font-medium">
                                            {setting.key}
                                        </td>
                                        <td className="px-4 py-3 text-zinc-600 dark:text-zinc-400">
                                            {setting.value ?? '—'}
                                        </td>
                                        <td className="px-4 py-3 text-right">
                                            <div className="flex items-center justify-end gap-4">
                                                <Dialog
                                                    open={editingId === setting.id}
                                                    onOpenChange={(open) => setEditingId(open ? setting.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-md">
                                                        <DialogHeader>
                                                            <DialogTitle>Edit setting</DialogTitle>
                                                            <DialogDescription>
                                                                Update the {setting.key} setting.
                                                            </DialogDescription>
                                                        </DialogHeader>

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

                                                                    <div className="flex flex-col gap-1">
                                                                        <label className="text-xs font-medium text-zinc-700 dark:text-zinc-300">
                                                                            Value
                                                                        </label>
                                                                        <input
                                                                            name="value"
                                                                            defaultValue={setting.value ?? ''}
                                                                            className="rounded-md border border-zinc-200 bg-white px-3 py-2 text-sm dark:border-zinc-800 dark:bg-zinc-950"
                                                                        />
                                                                        {errors.value && (
                                                                            <div className="text-xs text-red-600">
                                                                                {errors.value}
                                                                            </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({
                                                        integration: integration.id,
                                                        setting: setting.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>

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