import Pagination from '@/Components/Pagination';
import { router } from '@inertiajs/react';
import React from 'react';

type EntityOption = {
    key: string;
    label: string;
};

type AuditLogLink = {
    url: string | null;
    label: string;
    active: boolean;
};

type AuditLogRow = {
    id: number | string;
    entity_id: string;
    action: string;
    old_values: Record<string, unknown> | null;
    new_values: Record<string, unknown> | null;
    metadata: Record<string, unknown> | null;
    causer_type: string | null;
    causer_id: string | null;
    created_at: string;
};

type Paginator<T> = {
    data: T[];
    links: AuditLogLink[];
};

type Props = {
    entities: EntityOption[];
    selectedEntity: string;
    filters: {
        from: string;
        to: string;
        causer_id: string;
        action: string;
    };
    logs: Paginator<AuditLogRow>;
};

export default function AuditLogs({
    entities,
    selectedEntity,
    filters,
    logs,
}: Props) {
    const [openId, setOpenId] = React.useState<number | string | null>(null);

    const [form, setForm] = React.useState({
        entity: selectedEntity ?? entities[0]?.key ?? '',
        action: filters.action ?? '',
        from: filters.from ?? '',
        to: filters.to ?? '',
        causer_id: filters.causer_id ?? '',
    });

    function submit(e?: React.FormEvent, override: Partial<typeof form> = {}) {
        e?.preventDefault();

        router.get(
            route('admin.audit-logs.index'),
            { ...form, ...override },
            {
                preserveState: true,
                preserveScroll: true,
                replace: true,
            },
        );
    }

    function reset() {
        const empty = {
            entity: selectedEntity ?? entities[0]?.key ?? '',
            action: '',
            from: '',
            to: '',
            causer_id: '',
        };

        setForm(empty);
        submit(undefined, empty);
    }

    return (
        <div className="p-6">
            <h1 className="mb-4 text-xl font-semibold">Audit Logs</h1>

            {/* FILTRI */}
            <form
                onSubmit={submit}
                className="mb-4 flex flex-wrap items-end gap-3"
            >
                <div className="flex flex-col gap-1">
                    <label className="text-xs text-gray-600">Entità</label>
                    <select
                        className="h-10 rounded-md border border-gray-300 px-3 text-sm"
                        value={form.entity}
                        onChange={(e) => {
                            const v = e.target.value;
                            setForm((s) => ({ ...s, entity: v }));
                            setOpenId(null);
                            submit(undefined, { entity: v });
                        }}
                    >
                        {entities.map((e) => (
                            <option key={e.key} value={e.key}>
                                {e.label}
                            </option>
                        ))}
                    </select>
                </div>

                <div className="flex flex-col gap-1">
                    <label className="text-xs text-gray-600">Azione</label>
                    <select
                        className="h-10 rounded-md border border-gray-300 px-3 text-sm"
                        value={form.action}
                        onChange={(e) =>
                            setForm((s) => ({ ...s, action: e.target.value }))
                        }
                    >
                        <option value="">Tutte</option>
                        <option value="created">created</option>
                        <option value="updated">updated</option>
                        <option value="deleted">deleted</option>
                        <option value="restored">restored</option>
                    </select>
                </div>

                <div className="flex flex-col gap-1">
                    <label className="text-xs text-gray-600">Da</label>
                    <input
                        type="date"
                        className="h-10 rounded-md border border-gray-300 px-3 text-sm"
                        value={form.from}
                        onChange={(e) =>
                            setForm((s) => ({ ...s, from: e.target.value }))
                        }
                    />
                </div>

                <div className="flex flex-col gap-1">
                    <label className="text-xs text-gray-600">A</label>
                    <input
                        type="date"
                        className="h-10 rounded-md border border-gray-300 px-3 text-sm"
                        value={form.to}
                        onChange={(e) =>
                            setForm((s) => ({ ...s, to: e.target.value }))
                        }
                    />
                </div>

                <div className="flex flex-col gap-1">
                    <label className="text-xs text-gray-600">Causer ID</label>
                    <input
                        type="number"
                        className="h-10 w-40 rounded-md border border-gray-300 px-3 text-sm"
                        value={form.causer_id}
                        onChange={(e) =>
                            setForm((s) => ({
                                ...s,
                                causer_id: e.target.value,
                            }))
                        }
                    />
                </div>

                <div className="flex gap-2">
                    <button
                        type="submit"
                        className="h-10 rounded-md bg-black px-4 text-sm text-white"
                    >
                        Filtra
                    </button>
                    <button
                        type="button"
                        onClick={reset}
                        className="h-10 rounded-md border border-gray-300 px-4 text-sm"
                    >
                        Reset
                    </button>
                </div>
            </form>

            {/* TABELLA */}
            <div className="overflow-x-auto rounded-lg border border-gray-200 bg-white">
                <table className="min-w-full table-fixed text-sm">
                    <thead className="bg-gray-50 text-xs uppercase text-gray-500">
                        <tr>
                            <th className="w-12 px-4 py-3"></th>
                            <th className="w-56 px-4 py-3 text-left">Quando</th>
                            <th className="w-32 px-4 py-3 text-left">Azione</th>
                            <th className="w-32 px-4 py-3 text-left">
                                Entity ID
                            </th>
                            <th className="w-40 px-4 py-3 text-left">Causer</th>
                        </tr>
                    </thead>

                    <tbody className="divide-y">
                        {logs.data.map((log) => {
                            const isOpen = openId === log.id;
                            const causerType = (log.causer_type ?? '')
                                .split('\\')
                                .pop();

                            return (
                                <React.Fragment key={log.id}>
                                    <tr className="hover:bg-gray-50">
                                        <td className="w-12 px-4 py-3 text-center">
                                            <button
                                                onClick={() =>
                                                    setOpenId(
                                                        isOpen ? null : log.id,
                                                    )
                                                }
                                                className="inline-flex h-8 w-8 items-center justify-center rounded-md border border-gray-300 hover:bg-gray-100"
                                                title="Dettagli"
                                            >
                                                👁️
                                            </button>
                                        </td>
                                        <td className="w-56 whitespace-nowrap px-4 py-3">
                                            {log.created_at}
                                        </td>
                                        <td className="w-32 whitespace-nowrap px-4 py-3">
                                            {log.action}
                                        </td>
                                        <td className="w-32 whitespace-nowrap px-4 py-3">
                                            {log.entity_id}
                                        </td>
                                        <td className="w-40 whitespace-nowrap px-4 py-3">
                                            {causerType
                                                ? `${causerType} #${log.causer_id ?? '-'}`
                                                : (log.causer_id ?? '-')}
                                        </td>
                                    </tr>

                                    {isOpen && (
                                        <tr>
                                            <td
                                                colSpan={5}
                                                className="bg-gray-50 px-6 py-4"
                                            >
                                                <div className="grid grid-cols-1 gap-4 lg:grid-cols-3">
                                                    <div>
                                                        <div className="mb-2 text-xs font-semibold uppercase text-gray-500">
                                                            Old values
                                                        </div>
                                                        {log.old_values ? (
                                                            <pre className="whitespace-pre-wrap break-all rounded bg-white p-3 text-xs">
                                                                {JSON.stringify(
                                                                    log.old_values,
                                                                    null,
                                                                    2,
                                                                )}
                                                            </pre>
                                                        ) : (
                                                            <span className="text-gray-500">
                                                                —
                                                            </span>
                                                        )}
                                                    </div>

                                                    <div>
                                                        <div className="mb-2 text-xs font-semibold uppercase text-gray-500">
                                                            New values
                                                        </div>
                                                        {log.new_values ? (
                                                            <pre className="whitespace-pre-wrap break-all rounded bg-white p-3 text-xs">
                                                                {JSON.stringify(
                                                                    log.new_values,
                                                                    null,
                                                                    2,
                                                                )}
                                                            </pre>
                                                        ) : (
                                                            <span className="text-gray-500">
                                                                —
                                                            </span>
                                                        )}
                                                    </div>

                                                    <div>
                                                        <div className="mb-2 text-xs font-semibold uppercase text-gray-500">
                                                            Metadata
                                                        </div>
                                                        {log.metadata ? (
                                                            <pre className="whitespace-pre-wrap break-all rounded bg-white p-3 text-xs">
                                                                {JSON.stringify(
                                                                    log.metadata,
                                                                    null,
                                                                    2,
                                                                )}
                                                            </pre>
                                                        ) : (
                                                            <span className="text-gray-500">
                                                                —
                                                            </span>
                                                        )}
                                                    </div>
                                                </div>
                                            </td>
                                        </tr>
                                    )}
                                </React.Fragment>
                            );
                        })}

                        {logs.data.length === 0 && (
                            <tr>
                                <td
                                    colSpan={5}
                                    className="px-6 py-8 text-center text-gray-500"
                                >
                                    Nessun log trovato
                                </td>
                            </tr>
                        )}
                    </tbody>
                </table>
            </div>

            <Pagination links={logs.links} />
        </div>
    );
}
