import { Form, Head, usePage } 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 { index, store, update, destroy, send } from '@/routes/admin/reports';
import {
    store as storeSubscriber,
    update as updateSubscriber,
    destroy as destroySubscriber,
} from '@/routes/admin/reports/subscribers';

type Subscriber = {
    id: number;
    report_id: number;
    name: string;
    email: string;
    is_enabled: boolean;
};

type Report = {
    id: number;
    name: string;
    slug: string;
    description: string | null;
    is_enabled: boolean;
    subscribers_count: number;
    active_subscribers_count: number;
    subscribers: Subscriber[];
};

type Props = {
    reports: Report[];
};

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

export default function Reports({ reports }: Props) {
    const { props: { flash } } = usePage<{ flash: { success?: string } }>();
    const [createOpen, setCreateOpen] = useState(false);
    const [editingId, setEditingId] = useState<number | null>(null);
    const [subscribersReportId, setSubscribersReportId] = useState<number | null>(null);
    const [editingSubscriberId, setEditingSubscriberId] = useState<number | null>(null);
    const [addSubscriberOpen, setAddSubscriberOpen] = useState(false);
    const { sorted, sortColumn, sortDirection, toggleSort } = useSort<Report>(reports, 'name');

    const subscribersReport = reports.find((r) => r.id === subscribersReportId) ?? null;

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

            <h1 className="sr-only">Reports</h1>

            <div className="space-y-6">
                {flash?.success && (
                    <div className="rounded-md border border-green-200 bg-green-50 px-4 py-3 text-sm text-green-800 dark:border-green-800 dark:bg-green-900/20 dark:text-green-400">
                        {flash.success}
                    </div>
                )}
                <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
                    <HeadingSmall
                        title="Reports"
                        description="Manage automated reports and their subscriber lists."
                    />

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

                        <DialogContent className="sm:max-w-lg">
                            <DialogHeader>
                                <DialogTitle>Add report</DialogTitle>
                                <DialogDescription>
                                    Create a new automated report configuration.
                                </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="Daily Enrollment Summary"
                                            />
                                            {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"
                                                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="daily-enrollment-summary"
                                            />
                                            {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">
                                                Description
                                            </label>
                                            <textarea
                                                name="description"
                                                rows={2}
                                                className="rounded-md border border-zinc-200 bg-white px-3 py-2 text-sm dark:border-zinc-800 dark:bg-zinc-950"
                                                placeholder="Optional description"
                                            />
                                            {errors.description && (
                                                <div className="text-xs text-red-600">{errors.description}</div>
                                            )}
                                        </div>

                                        <div className="flex items-center gap-2">
                                            <input type="hidden" name="is_enabled" value="0" />
                                            <input
                                                type="checkbox"
                                                name="is_enabled"
                                                id="create-is-enabled"
                                                value="1"
                                                defaultChecked
                                                className="rounded"
                                            />
                                            <label htmlFor="create-is-enabled" className="text-sm text-zinc-700 dark:text-zinc-300">
                                                Enabled
                                            </label>
                                        </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 report
                                            </button>
                                        </div>
                                    </div>
                                )}
                            </Form>
                        </DialogContent>
                    </Dialog>
                </div>

                {/* Reports 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}
                                    />
                                    <th className="px-4 py-3">Slug</th>
                                    <th className="px-4 py-3">Status</th>
                                    <th className="px-4 py-3">Subscribers</th>
                                    <th className="px-4 py-3" />
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-zinc-200 dark:divide-zinc-800">
                                {sorted.map((r) => (
                                    <tr key={r.id}>
                                        <td className="px-4 py-3 font-medium">
                                            {r.name}
                                            {r.description && (
                                                <p className="text-xs font-normal text-zinc-500 dark:text-zinc-400">
                                                    {r.description}
                                                </p>
                                            )}
                                        </td>
                                        <td className="px-4 py-3 font-mono text-xs text-zinc-600 dark:text-zinc-400">
                                            {r.slug}
                                        </td>
                                        <td className="px-4 py-3">
                                            {r.is_enabled ? (
                                                <span className="inline-flex items-center rounded-full bg-green-100 px-2 py-0.5 text-xs font-medium text-green-800 dark:bg-green-900/30 dark:text-green-400">
                                                    Enabled
                                                </span>
                                            ) : (
                                                <span className="inline-flex items-center rounded-full bg-zinc-100 px-2 py-0.5 text-xs font-medium text-zinc-600 dark:bg-zinc-800 dark:text-zinc-400">
                                                    Disabled
                                                </span>
                                            )}
                                        </td>
                                        <td className="px-4 py-3 text-sm">
                                            <span className="font-medium">{r.active_subscribers_count}</span>
                                            <span className="text-zinc-400"> / {r.subscribers_count}</span>
                                            <span className="ml-1 text-xs text-zinc-400">active</span>
                                        </td>
                                        <td className="px-4 py-3 text-right">
                                            <div className="flex items-center justify-end gap-4">
                                                <Form method="post" action={send.url(r.id)}>
                                                    {({ processing }) => (
                                                        <button
                                                            type="submit"
                                                            disabled={processing}
                                                            className="text-sm text-zinc-700 hover:underline disabled:opacity-60 dark:text-zinc-300"
                                                        >
                                                            Send now
                                                        </button>
                                                    )}
                                                </Form>

                                                <button
                                                    type="button"
                                                    onClick={() => {
                                                        setSubscribersReportId(r.id);
                                                        setAddSubscriberOpen(false);
                                                        setEditingSubscriberId(null);
                                                    }}
                                                    className="text-sm text-blue-700 hover:underline dark:text-blue-400"
                                                >
                                                    Subscribers
                                                </button>

                                                <Dialog
                                                    open={editingId === r.id}
                                                    onOpenChange={(open) => setEditingId(open ? r.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 report</DialogTitle>
                                                            <DialogDescription>
                                                                Update {r.name} settings.
                                                            </DialogDescription>
                                                        </DialogHeader>

                                                        <Form
                                                            method="put"
                                                            action={update.url(r.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={r.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={r.slug}
                                                                            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.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">
                                                                            Description
                                                                        </label>
                                                                        <textarea
                                                                            name="description"
                                                                            rows={2}
                                                                            defaultValue={r.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 items-center gap-2">
                                                                        <input type="hidden" name="is_enabled" value="0" />
                                                                        <input
                                                                            type="checkbox"
                                                                            name="is_enabled"
                                                                            id={`edit-is-enabled-${r.id}`}
                                                                            value="1"
                                                                            defaultChecked={r.is_enabled}
                                                                            className="rounded"
                                                                        />
                                                                        <label
                                                                            htmlFor={`edit-is-enabled-${r.id}`}
                                                                            className="text-sm text-zinc-700 dark:text-zinc-300"
                                                                        >
                                                                            Enabled
                                                                        </label>
                                                                    </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(r.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>

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

                {/* Subscribers panel */}
                {subscribersReport && (
                    <div className="space-y-4">
                        <div className="flex items-center justify-between">
                            <div>
                                <h2 className="text-sm font-semibold text-zinc-900 dark:text-zinc-100">
                                    Subscribers — {subscribersReport.name}
                                </h2>
                                <p className="text-xs text-zinc-500">
                                    People who receive this report by email.
                                </p>
                            </div>
                            <div className="flex items-center gap-3">
                                <Dialog open={addSubscriberOpen} onOpenChange={setAddSubscriberOpen}>
                                    <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 subscriber
                                        </button>
                                    </DialogTrigger>

                                    <DialogContent className="sm:max-w-md">
                                        <DialogHeader>
                                            <DialogTitle>Add subscriber</DialogTitle>
                                            <DialogDescription>
                                                Add a new recipient for the {subscribersReport.name} report.
                                            </DialogDescription>
                                        </DialogHeader>

                                        <Form
                                            method="post"
                                            action={storeSubscriber.url(subscribersReport.id)}
                                            resetOnSuccess
                                            onSuccess={() => setAddSubscriberOpen(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="Jane Smith"
                                                        />
                                                        {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">
                                                            Email
                                                        </label>
                                                        <input
                                                            name="email"
                                                            type="email"
                                                            className="rounded-md border border-zinc-200 bg-white px-3 py-2 text-sm dark:border-zinc-800 dark:bg-zinc-950"
                                                            placeholder="jane@example.com"
                                                        />
                                                        {errors.email && (
                                                            <div className="text-xs text-red-600">{errors.email}</div>
                                                        )}
                                                    </div>

                                                    <div className="flex items-center gap-2">
                                                        <input type="hidden" name="is_enabled" value="0" />
                                                        <input
                                                            type="checkbox"
                                                            name="is_enabled"
                                                            id="add-sub-is-enabled"
                                                            value="1"
                                                            defaultChecked
                                                            className="rounded"
                                                        />
                                                        <label htmlFor="add-sub-is-enabled" className="text-sm text-zinc-700 dark:text-zinc-300">
                                                            Enabled
                                                        </label>
                                                    </div>

                                                    <div className="flex items-end justify-end gap-3">
                                                        <button
                                                            type="button"
                                                            onClick={() => setAddSubscriberOpen(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 subscriber
                                                        </button>
                                                    </div>
                                                </div>
                                            )}
                                        </Form>
                                    </DialogContent>
                                </Dialog>

                                <button
                                    type="button"
                                    onClick={() => setSubscribersReportId(null)}
                                    className="text-sm text-zinc-500 hover:text-zinc-900 dark:hover:text-zinc-100"
                                >
                                    Close
                                </button>
                            </div>
                        </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">Name</th>
                                            <th className="px-4 py-3">Email</th>
                                            <th className="px-4 py-3">Status</th>
                                            <th className="px-4 py-3" />
                                        </tr>
                                    </thead>
                                    <tbody className="divide-y divide-zinc-200 dark:divide-zinc-800">
                                        {subscribersReport.subscribers.map((sub) => (
                                            <tr key={sub.id}>
                                                <td className="px-4 py-3 font-medium">{sub.name}</td>
                                                <td className="px-4 py-3 text-zinc-600 dark:text-zinc-400">{sub.email}</td>
                                                <td className="px-4 py-3">
                                                    {sub.is_enabled ? (
                                                        <span className="inline-flex items-center rounded-full bg-green-100 px-2 py-0.5 text-xs font-medium text-green-800 dark:bg-green-900/30 dark:text-green-400">
                                                            Active
                                                        </span>
                                                    ) : (
                                                        <span className="inline-flex items-center rounded-full bg-zinc-100 px-2 py-0.5 text-xs font-medium text-zinc-600 dark:bg-zinc-800 dark:text-zinc-400">
                                                            Inactive
                                                        </span>
                                                    )}
                                                </td>
                                                <td className="px-4 py-3 text-right">
                                                    <div className="flex items-center justify-end gap-4">
                                                        <Dialog
                                                            open={editingSubscriberId === sub.id}
                                                            onOpenChange={(open) =>
                                                                setEditingSubscriberId(open ? sub.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 subscriber</DialogTitle>
                                                                    <DialogDescription>
                                                                        Update {sub.name}'s subscription details.
                                                                    </DialogDescription>
                                                                </DialogHeader>

                                                                <Form
                                                                    method="put"
                                                                    action={updateSubscriber.url({
                                                                        report: subscribersReport.id,
                                                                        subscriber: sub.id,
                                                                    })}
                                                                    onSuccess={() => setEditingSubscriberId(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={sub.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">
                                                                                    Email
                                                                                </label>
                                                                                <input
                                                                                    name="email"
                                                                                    type="email"
                                                                                    defaultValue={sub.email}
                                                                                    className="rounded-md border border-zinc-200 bg-white px-3 py-2 text-sm dark:border-zinc-800 dark:bg-zinc-950"
                                                                                />
                                                                                {errors.email && (
                                                                                    <div className="text-xs text-red-600">{errors.email}</div>
                                                                                )}
                                                                            </div>

                                                                            <div className="flex items-center gap-2">
                                                                                <input type="hidden" name="is_enabled" value="0" />
                                                                                <input
                                                                                    type="checkbox"
                                                                                    name="is_enabled"
                                                                                    id={`edit-sub-enabled-${sub.id}`}
                                                                                    value="1"
                                                                                    defaultChecked={sub.is_enabled}
                                                                                    className="rounded"
                                                                                />
                                                                                <label
                                                                                    htmlFor={`edit-sub-enabled-${sub.id}`}
                                                                                    className="text-sm text-zinc-700 dark:text-zinc-300"
                                                                                >
                                                                                    Enabled
                                                                                </label>
                                                                            </div>

                                                                            <div className="flex items-end justify-end gap-3">
                                                                                <button
                                                                                    type="button"
                                                                                    onClick={() => setEditingSubscriberId(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={destroySubscriber.url({
                                                                report: subscribersReport.id,
                                                                subscriber: sub.id,
                                                            })}
                                                        >
                                                            {({ processing }) => (
                                                                <button
                                                                    type="submit"
                                                                    disabled={processing}
                                                                    className="text-sm text-red-700 hover:underline disabled:opacity-60 dark:text-red-400"
                                                                >
                                                                    Remove
                                                                </button>
                                                            )}
                                                        </Form>
                                                    </div>
                                                </td>
                                            </tr>
                                        ))}
                                    </tbody>
                                </table>
                            </div>

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