import { Head, router } from '@inertiajs/react';
import {
    Search,
    Eye,
    Trash2,
    ShieldAlert,
    Terminal,
    ArrowLeft,
    ArrowRight,
} from 'lucide-react';
import { useState } from 'react';
import { toast } from 'sonner';
import { destroy as destroyLog } from '@/routes/settings/audit-logs';
import { Button } from '@/components/ui/button';
import { Card } from '@/components/ui/card';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import AppLayout from '@/layouts/app-layout';

interface User {
    id: number;
    name: string;
    email: string;
}

interface AuditLog {
    id: number;
    user_id: number | null;
    ip_address: string;
    http_method: string;
    endpoint: string;
    request_payload: Record<string, any> | null;
    response_status_code: number;
    db_latency_ms: number | null;
    total_response_time_ms: number | null;
    created_at: string;
    user?: User | null;
}

interface PaginationLink {
    url: string | null;
    label: string;
    active: boolean;
}

interface PaginatedLogs {
    data: AuditLog[];
    current_page: number;
    last_page: number;
    prev_page_url: string | null;
    next_page_url: string | null;
    links: PaginationLink[];
    total: number;
}

interface Props {
    logs: PaginatedLogs;
    filters: {
        search?: string;
    };
}

export default function AuditLogsPage({ logs, filters }: Props) {
    const [search, setSearch] = useState(filters.search || '');
    const [viewingPayload, setViewingPayload] = useState<AuditLog | null>(null);

    const handleSearchSubmit = (e: React.FormEvent) => {
        e.preventDefault();
        router.get(
            '/settings/audit-logs',
            { search },
            { preserveState: true },
        );
    };

    const handleDelete = (id: number) => {
        if (confirm('Are you sure you want to delete this log entry?')) {
            router.delete(destroyLog.url(id), {
                onSuccess: () => {
                    toast.success('Log deleted successfully.');
                },
            });
        }
    };

    const getStatusColor = (code: number) => {
        if (code >= 500) {
            return 'text-red-650 bg-red-50 border-red-200 dark:bg-red-950/50 dark:text-red-400';
        }

        if (code >= 400) {
            return 'text-orange-655 bg-orange-50 border-orange-200 dark:bg-orange-950/50 dark:text-orange-400';
        }

        if (code >= 300) {
            return 'text-blue-650 bg-blue-50 border-blue-200 dark:bg-blue-950/50 dark:text-blue-400';
        }

        return 'text-emerald-650 bg-emerald-50 border-emerald-200 dark:bg-emerald-950/50 dark:text-emerald-400';
    };

    const getMethodColor = (method: string) => {
        switch (method.toUpperCase()) {
            case 'POST':
                return 'bg-emerald-500 text-white';
            case 'PUT':
            case 'PATCH':
                return 'bg-blue-500 text-white';
            case 'DELETE':
                return 'bg-red-500 text-white';
            default:
                return 'bg-zinc-550 text-white';
        }
    };

    return (
        <>
            <Head title="Platform Security Audit Logs" />
            <div className="from-zinc-550/20 min-h-screen w-full space-y-8 bg-gradient-to-b via-transparent to-transparent p-6 md:p-10">
                {/* Premium Gradient Header Banner */}
                <div className="relative flex flex-col items-start justify-between gap-6 overflow-hidden rounded-3xl border border-white/10 bg-gradient-to-r from-zinc-900 via-zinc-800 to-indigo-950 p-8 text-white shadow-2xl md:flex-row md:items-center md:p-10">
                    <div className="absolute inset-0 bg-[radial-gradient(circle_at_top_right,rgba(255,255,255,0.1),transparent_50%)]" />
                    <div className="relative max-w-2xl space-y-2">
                        <span className="rounded-full border border-white/10 bg-white/10 px-3 py-1 text-[10px] font-extrabold tracking-widest text-white/90 uppercase backdrop-blur-md">
                            Security Operations
                        </span>
                        <h3 className="text-2xl font-extrabold tracking-tight md:text-3xl">
                            Platform Security Audit Logs
                        </h3>
                        <p className="text-zinc-350 text-sm font-medium">
                            Trace real-time operational events, inspect endpoint
                            latencies, and review HTTP raw payloads for security
                            auditing.
                        </p>
                    </div>
                </div>

                {/* Filters and Search Toolbar */}
                <div className="flex flex-col items-center gap-4 rounded-2xl border border-zinc-200/80 bg-white/60 p-5 shadow-sm backdrop-blur-2xl sm:flex-row dark:border-zinc-800/80 dark:bg-zinc-900/60">
                    <form
                        onSubmit={handleSearchSubmit}
                        className="flex w-full items-center gap-2"
                    >
                        <div className="relative w-full">
                            <Search className="absolute top-1/2 left-3.5 size-4 -translate-y-1/2 text-zinc-400" />
                            <Input
                                className="h-11 rounded-xl border-zinc-200 bg-white/80 pl-10 text-xs shadow-inner focus-visible:ring-zinc-500/50 dark:border-zinc-800 dark:bg-zinc-950/80"
                                placeholder="Search logs by API endpoint route, method, operator name/email, or IP address..."
                                value={search}
                                onChange={(e) => setSearch(e.target.value)}
                            />
                        </div>
                        <Button
                            type="submit"
                            className="h-11 rounded-xl bg-zinc-900 px-5 font-bold text-white shadow-md hover:bg-zinc-800 dark:bg-zinc-100 dark:text-zinc-950"
                        >
                            Search
                        </Button>
                    </form>
                </div>

                {logs.data.length === 0 ? (
                    <Card className="flex flex-col items-center justify-center rounded-3xl border-2 border-dashed border-zinc-200 bg-white/30 p-16 text-center backdrop-blur-sm dark:border-zinc-800 dark:bg-zinc-950/10">
                        <div className="bg-zinc-550/20 mb-4 animate-pulse rounded-full p-4">
                            <ShieldAlert className="size-8 text-zinc-500" />
                        </div>
                        <p className="text-base font-bold text-zinc-800 dark:text-zinc-200">
                            No matching audit logs found
                        </p>
                    </Card>
                ) : (
                    <div className="space-y-4">
                        <div className="overflow-hidden rounded-3xl border border-zinc-200/80 bg-white/60 shadow-xl backdrop-blur-2xl transition-all duration-500 dark:border-zinc-800/80 dark:bg-zinc-900/60">
                            <table className="w-full border-collapse text-left text-xs">
                                <thead>
                                    <tr className="border-b border-zinc-200 bg-zinc-50/80 text-[10px] font-bold tracking-wider text-zinc-500 uppercase select-none dark:border-zinc-800 dark:bg-zinc-900/50">
                                        <th className="p-5 pl-8">Operator</th>
                                        <th className="p-5">Method & Route</th>
                                        <th className="p-5 text-center">
                                            Status
                                        </th>
                                        <th className="p-5 text-right">
                                            Latency
                                        </th>
                                        <th className="w-[150px] p-5 pr-8 text-right">
                                            Actions
                                        </th>
                                    </tr>
                                </thead>
                                <tbody className="divide-y divide-zinc-100 dark:divide-zinc-800/80">
                                    {logs.data.map((log) => (
                                        <tr
                                            key={log.id}
                                            className="dark:hover:bg-zinc-850/5 group transition-all duration-300 hover:bg-zinc-50/10"
                                        >
                                            <td className="p-5 pl-8">
                                                <div className="text-sm font-extrabold text-zinc-900 dark:text-zinc-100">
                                                    {log.user?.name ?? (
                                                        <span className="text-zinc-450 dark:text-zinc-550 font-semibold italic">
                                                            Guest Operator
                                                        </span>
                                                    )}
                                                </div>
                                                <div className="mt-0.5 text-[10px] font-medium text-zinc-400">
                                                    IP: {log.ip_address}
                                                </div>
                                            </td>
                                            <td className="p-5">
                                                <div className="flex min-w-0 items-center gap-2">
                                                    <span
                                                        className={`shrink-0 rounded px-2 py-0.5 text-[8px] leading-tight font-extrabold uppercase ${getMethodColor(log.http_method)}`}
                                                    >
                                                        {log.http_method}
                                                    </span>
                                                    <span className="max-w-[280px] truncate text-xs font-semibold text-zinc-700 sm:max-w-[420px] dark:text-zinc-300">
                                                        {log.endpoint}
                                                    </span>
                                                </div>
                                                <div className="mt-0.5 text-[10px] font-medium text-zinc-400">
                                                    {new Date(
                                                        log.created_at,
                                                    ).toLocaleString()}
                                                </div>
                                            </td>
                                            <td className="p-5 text-center">
                                                <span
                                                    className={`inline-block rounded-full border px-2.5 py-0.5 text-[10px] font-bold ${getStatusColor(log.response_status_code)}`}
                                                >
                                                    {log.response_status_code}
                                                </span>
                                            </td>
                                            <td className="p-5 text-right text-xs font-semibold text-zinc-600 dark:text-zinc-400">
                                                <div>
                                                    {log.total_response_time_ms
                                                        ? `${Math.round(log.total_response_time_ms)}ms`
                                                        : '-'}
                                                </div>
                                                <div className="mt-0.5 text-[9px] font-medium text-zinc-400">
                                                    DB:{' '}
                                                    {log.db_latency_ms
                                                        ? `${Math.round(log.db_latency_ms)}ms`
                                                        : '-'}
                                                </div>
                                            </td>
                                            <td className="p-5 pr-8 text-right">
                                                <div className="flex items-center justify-end gap-1.5 opacity-0 transition-opacity duration-300 group-hover:opacity-100">
                                                    <Button
                                                        variant="ghost"
                                                        size="icon"
                                                        className="size-8 rounded-lg text-zinc-500 hover:bg-zinc-100 hover:text-zinc-900 dark:hover:bg-zinc-800"
                                                        onClick={() =>
                                                            setViewingPayload(
                                                                log,
                                                            )
                                                        }
                                                    >
                                                        <Eye className="size-3.5" />
                                                    </Button>
                                                    <Button
                                                        variant="ghost"
                                                        size="icon"
                                                        className="size-8 rounded-lg text-red-500 hover:bg-red-50 hover:text-red-600 dark:hover:bg-red-950/20"
                                                        onClick={() =>
                                                            handleDelete(log.id)
                                                        }
                                                    >
                                                        <Trash2 className="size-3.5" />
                                                    </Button>
                                                </div>
                                            </td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        </div>

                        {/* Pagination */}
                        {logs.last_page > 1 && (
                            <div className="flex items-center justify-between border-t border-zinc-100 pt-4 dark:border-zinc-800/80">
                                <span className="text-xs text-zinc-400">
                                    Page {logs.current_page} of {logs.last_page}{' '}
                                    ({logs.total} total logs)
                                </span>
                                <div className="flex items-center gap-1.5">
                                    {logs.links.map((link, idx) => {
                                        if (link.label.includes('Previous')) {
                                            return (
                                                <Button
                                                    key={idx}
                                                    variant="outline"
                                                    size="icon"
                                                    className="size-8 rounded-lg"
                                                    disabled={!link.url}
                                                    onClick={() =>
                                                        link.url &&
                                                        router.get(link.url)
                                                    }
                                                >
                                                    <ArrowLeft className="size-3.5" />
                                                </Button>
                                            );
                                        }

                                        if (link.label.includes('Next')) {
                                            return (
                                                <Button
                                                    key={idx}
                                                    variant="outline"
                                                    size="icon"
                                                    className="size-8 rounded-lg"
                                                    disabled={!link.url}
                                                    onClick={() =>
                                                        link.url &&
                                                        router.get(link.url)
                                                    }
                                                >
                                                    <ArrowRight className="size-3.5" />
                                                </Button>
                                            );
                                        }

                                        const pageNum = parseInt(link.label);

                                        if (isNaN(pageNum)) {
                                            return null;
                                        }

                                        const isClose =
                                            Math.abs(
                                                pageNum - logs.current_page,
                                            ) <= 1;

                                        if (
                                            !isClose &&
                                            pageNum !== 1 &&
                                            pageNum !== logs.last_page
                                        ) {
                                            return null;
                                        }

                                        return (
                                            <Button
                                                key={idx}
                                                variant={
                                                    link.active
                                                        ? 'default'
                                                        : 'outline'
                                                }
                                                size="sm"
                                                className="h-8 min-w-8 rounded-lg px-2 text-xs"
                                                onClick={() =>
                                                    router.get(link.url || '')
                                                }
                                            >
                                                {link.label}
                                            </Button>
                                        );
                                    })}
                                </div>
                            </div>
                        )}
                    </div>
                )}

                {/* Payload View Dialog */}
                <Dialog
                    open={!!viewingPayload}
                    onOpenChange={(open) => !open && setViewingPayload(null)}
                >
                    <DialogContent className="max-w-lg rounded-2xl">
                        <DialogHeader>
                            <DialogTitle className="flex items-center gap-2">
                                <Terminal className="size-5 text-indigo-500" />{' '}
                                Payload Details
                            </DialogTitle>
                            <DialogDescription>
                                HTTP request parameters and performance
                                profiles.
                            </DialogDescription>
                        </DialogHeader>
                        {viewingPayload && (
                            <div className="space-y-4 pt-2 text-xs">
                                <div className="grid grid-cols-2 gap-4 rounded-xl border border-zinc-100 bg-zinc-50 p-3 font-medium text-zinc-500 dark:border-zinc-800/80 dark:bg-zinc-900/50">
                                    <div>
                                        <span className="block text-[10px] font-bold text-zinc-400 uppercase">
                                            Method
                                        </span>
                                        <span className="font-extrabold text-zinc-800 dark:text-zinc-200">
                                            {viewingPayload.http_method}
                                        </span>
                                    </div>
                                    <div>
                                        <span className="block text-[10px] font-bold text-zinc-400 uppercase">
                                            Status
                                        </span>
                                        <span className="font-extrabold text-zinc-800 dark:text-zinc-200">
                                            {
                                                viewingPayload.response_status_code
                                            }
                                        </span>
                                    </div>
                                    <div className="col-span-2">
                                        <span className="block text-[10px] font-bold text-zinc-400 uppercase">
                                            Route
                                        </span>
                                        <span className="text-zinc-850 dark:text-zinc-150 font-bold break-all">
                                            {viewingPayload.endpoint}
                                        </span>
                                    </div>
                                </div>

                                <div className="space-y-1">
                                    <Label className="text-[10px] font-bold text-zinc-400 uppercase">
                                        Request Payload
                                    </Label>
                                    <pre className="max-h-48 scrollbar-thin overflow-auto rounded-xl bg-zinc-900 p-4 font-mono text-zinc-200">
                                        {viewingPayload.request_payload
                                            ? JSON.stringify(
                                                  viewingPayload.request_payload,
                                                  null,
                                                  2,
                                              )
                                            : 'No payload content (GET/DELETE request).'}
                                    </pre>
                                </div>
                            </div>
                        )}
                    </DialogContent>
                </Dialog>
            </div>
        </>
    );
}

AuditLogsPage.layout = (page: React.ReactNode) => <AppLayout>{page}</AppLayout>;
