import AdminLayout from '@/Layouts/AdminLayout';
import { Badge } from '@/components/ui/badge';
import { parseServerDate } from '@/lib/date';
import { cn } from '@/lib/utils';
import { Head, Link } from '@inertiajs/react';
import { format, formatDistanceToNow } from 'date-fns';
import {
    ArrowLeft,
    ArrowRight,
    CheckCircle,
    Clock,
    Flag,
    Globe,
    Hash,
    Layers,
    MessageSquare,
    ShieldAlert,
    Tag,
    Terminal,
    User,
    XCircle,
} from 'lucide-react';
import { useState } from 'react';
import NoteForm, { type Note } from './components/NoteForm';
import { SeverityBadge } from './components/SeverityBadge';
import {
    ReviewBadge,
    StatusBadge,
    type ReviewStatus,
} from './components/StatusBadge';

// ── Types ─────────────────────────────────────────────────────────────────────

interface AuditLogDetail {
    id: string;
    scope: string;
    event: string;
    category: string;
    action: string;
    status: string;
    severity: string;
    actor_type: string;
    actor_name: string | null;
    actor_role: string | null;
    auditable_type: string | null;
    actor_id: string | null;
    auditable_id: string | null;
    ip_address: string | null;
    user_agent: string | null;
    url: string | null;
    http_method: string | null;
    branch_id: string | null;
    review_status: ReviewStatus;
    reviewed_at: string | null;
    reviewed_by_name: string | null;
    created_at: string;
    changes: {
        field: string;
        old_value: string | null;
        new_value: string | null;
    }[];
    tags: { key: string; value: string }[];
    notes: Note[];
}

interface Props {
    log: AuditLogDetail;
}

// ── Helpers ───────────────────────────────────────────────────────────────────

function Section({
    title,
    icon: Icon,
    children,
}: {
    title: string;
    icon: React.ComponentType<{ className?: string }>;
    children: React.ReactNode;
}) {
    return (
        <div className="space-y-3">
            <div className="text-muted-foreground flex items-center gap-2 text-xs font-semibold tracking-widest uppercase">
                <Icon className="h-3.5 w-3.5" />
                {title}
            </div>
            {children}
        </div>
    );
}

function DataRow({
    label,
    value,
    mono = false,
}: {
    label: string;
    value: React.ReactNode;
    mono?: boolean;
}) {
    return (
        <div className="flex items-start justify-between gap-4 py-2">
            <span className="text-muted-foreground shrink-0 text-xs">
                {label}
            </span>
            <span
                className={cn(
                    'text-foreground text-right text-xs',
                    mono && 'font-mono',
                )}
            >
                {value ?? '—'}
            </span>
        </div>
    );
}

const NOTE_CONFIG: Record<
    string,
    {
        icon: React.ComponentType<{ className?: string }>;
        label: string;
        color: string;
    }
> = {
    note: {
        icon: MessageSquare,
        label: 'Added a note',
        color: 'text-foreground bg-card border-border',
    },
    reviewed: {
        icon: CheckCircle,
        label: 'Marked as reviewed',
        color: 'text-green-700 dark:text-green-400 bg-green-500/5 border-green-500/20',
    },
    escalated: {
        icon: ShieldAlert,
        label: 'Escalated',
        color: 'text-red-700 dark:text-red-400 bg-red-500/5 border-red-500/20',
    },
    resolved: {
        icon: Flag,
        label: 'Resolved',
        color: 'text-blue-700 dark:text-blue-400 bg-blue-500/5 border-blue-500/20',
    },
    false_positive: {
        icon: XCircle,
        label: 'Marked false positive',
        color: 'text-muted-foreground bg-muted/50 border-border',
    },
};

// ── Page ──────────────────────────────────────────────────────────────────────

export default function AuditLogsShow({ log }: Props) {
    const [notes, setNotes] = useState<Note[]>(log.notes);
    const [reviewState, setReviewState] = useState({
        status: log.review_status,
        at: log.reviewed_at,
        by: log.reviewed_by_name,
    });

    const modelName = log.auditable_type?.split('\\').pop();

    const handleNoteSuccess = (result: {
        note: Note;
        review_status: ReviewStatus;
        reviewed_at: string | null;
        reviewed_by_name: string | null;
    }) => {
        setNotes((prev) => [result.note, ...prev]);
        setReviewState({
            status: result.review_status,
            at: result.reviewed_at,
            by: result.reviewed_by_name,
        });
    };

    return (
        <AdminLayout
            title="Audit Log"
            breadcrumbs={[
                { label: 'System' },
                { label: 'Audit Logs', href: '/admin/audit' },
                { label: `#${log.id}` },
            ]}
        >
            <Head title={`Audit Log #${log.id}`} />

            <div className="p-6 lg:p-8">
                {/* Back */}
                <Link
                    href="/admin/audit"
                    className="text-muted-foreground hover:text-foreground mb-6 inline-flex items-center gap-1.5 text-xs transition-colors"
                >
                    <ArrowLeft className="h-3.5 w-3.5" />
                    Back to audit logs
                </Link>

                {/* Event header card */}
                <div className="border-border bg-card mb-6 rounded-xl border p-6">
                    <div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
                        <div className="space-y-2">
                            <div className="flex flex-wrap items-center gap-2">
                                <SeverityBadge severity={log.severity} />
                                <StatusBadge status={log.status} />
                                <ReviewBadge status={reviewState.status} />
                                <Badge
                                    variant="outline"
                                    className="font-mono text-[10px]"
                                >
                                    {log.scope}
                                </Badge>
                            </div>
                            <h1 className="text-foreground font-mono text-xl font-bold">
                                {log.event}
                            </h1>
                            <p className="text-muted-foreground text-sm">
                                {format(
                                    parseServerDate(log.created_at),
                                    "EEEE, d MMMM yyyy 'at' HH:mm:ss",
                                )}
                                <span className="ml-2 text-xs">
                                    (
                                    {formatDistanceToNow(
                                        parseServerDate(log.created_at),
                                        { addSuffix: true },
                                    )}
                                    )
                                </span>
                            </p>
                        </div>
                        <div className="text-muted-foreground flex shrink-0 items-center gap-2 text-xs">
                            <Hash className="h-3.5 w-3.5" />
                            <span className="font-mono">#{log.id}</span>
                        </div>
                    </div>

                    {reviewState.status && reviewState.at && (
                        <div className="border-border bg-muted/30 text-muted-foreground mt-4 rounded-lg border px-4 py-2.5 text-xs">
                            <span className="font-semibold capitalize">
                                {reviewState.status.replace('_', ' ')}
                            </span>
                            {' by '}
                            <span className="text-foreground">
                                {reviewState.by}
                            </span>
                            {' · '}
                            {format(
                                parseServerDate(reviewState.at),
                                "d MMM yyyy 'at' HH:mm",
                            )}
                        </div>
                    )}
                </div>

                <div className="grid gap-6 lg:grid-cols-[1fr_380px]">
                    {/* ── Left column ── */}
                    <div className="space-y-6">
                        {/* Actor + Request */}
                        <div className="border-border bg-card divide-border divide-y rounded-xl border">
                            <div className="p-5">
                                <Section title="Actor" icon={User}>
                                    <div className="divide-border border-border divide-y rounded-lg border">
                                        <DataRow
                                            label="Name"
                                            value={log.actor_name}
                                        />
                                        <DataRow
                                            label="Type"
                                            value={
                                                <span className="font-mono">
                                                    {log.actor_type}
                                                </span>
                                            }
                                        />
                                        <DataRow
                                            label="Role"
                                            value={log.actor_role}
                                        />
                                        <DataRow
                                            label="Actor ID"
                                            value={
                                                log.actor_id ? (
                                                    <span className="font-mono">
                                                        #{log.actor_id}
                                                    </span>
                                                ) : null
                                            }
                                        />
                                    </div>
                                </Section>
                            </div>

                            <div className="p-5">
                                <Section title="Request Context" icon={Globe}>
                                    <div className="divide-border border-border divide-y rounded-lg border">
                                        <DataRow
                                            label="IP Address"
                                            value={log.ip_address}
                                            mono
                                        />
                                        <DataRow
                                            label="Method"
                                            value={log.http_method}
                                            mono
                                        />
                                        <DataRow
                                            label="URL"
                                            value={
                                                log.url ? (
                                                    <span className="break-all">
                                                        {log.url}
                                                    </span>
                                                ) : null
                                            }
                                            mono
                                        />
                                        <DataRow
                                            label="User Agent"
                                            value={
                                                log.user_agent ? (
                                                    <span className="line-clamp-2 text-left">
                                                        {log.user_agent}
                                                    </span>
                                                ) : null
                                            }
                                        />
                                    </div>
                                </Section>
                            </div>

                            {modelName && (
                                <div className="p-5">
                                    <Section
                                        title="Affected Record"
                                        icon={Layers}
                                    >
                                        <div className="divide-border border-border divide-y rounded-lg border">
                                            <DataRow
                                                label="Model"
                                                value={
                                                    <span className="font-mono">
                                                        {modelName}
                                                    </span>
                                                }
                                            />
                                            <DataRow
                                                label="ID"
                                                value={
                                                    <span className="font-mono">
                                                        #{log.auditable_id}
                                                    </span>
                                                }
                                            />
                                        </div>
                                    </Section>
                                </div>
                            )}
                        </div>

                        {/* Field changes */}
                        {log.changes.length > 0 && (
                            <div className="border-border bg-card rounded-xl border p-5">
                                <Section
                                    title={`Field Changes (${log.changes.length})`}
                                    icon={Terminal}
                                >
                                    <div className="border-border overflow-hidden rounded-lg border">
                                        <table className="w-full text-xs">
                                            <thead>
                                                <tr className="border-border bg-muted/50 border-b">
                                                    <th className="text-muted-foreground px-3 py-2 text-left font-semibold">
                                                        Field
                                                    </th>
                                                    <th className="text-muted-foreground px-3 py-2 text-left font-semibold">
                                                        Before
                                                    </th>
                                                    <th className="w-6" />
                                                    <th className="text-muted-foreground px-3 py-2 text-left font-semibold">
                                                        After
                                                    </th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                {log.changes.map((c, i) => (
                                                    <tr
                                                        key={i}
                                                        className={cn(
                                                            i > 0 &&
                                                                'border-border border-t',
                                                            'hover:bg-muted/20',
                                                        )}
                                                    >
                                                        <td className="text-foreground px-3 py-2.5 font-mono font-medium">
                                                            {c.field}
                                                        </td>
                                                        <td className="px-3 py-2.5">
                                                            <span className="rounded bg-red-500/10 px-1.5 py-0.5 font-mono text-red-700 dark:text-red-400">
                                                                {c.old_value ?? (
                                                                    <span className="text-muted-foreground italic">
                                                                        empty
                                                                    </span>
                                                                )}
                                                            </span>
                                                        </td>
                                                        <td className="text-muted-foreground dark:text-muted-foreground/60 text-center">
                                                            <ArrowRight className="h-3 w-3" />
                                                        </td>
                                                        <td className="px-3 py-2.5">
                                                            <span className="rounded bg-green-500/10 px-1.5 py-0.5 font-mono text-green-700 dark:text-green-400">
                                                                {c.new_value ?? (
                                                                    <span className="text-muted-foreground italic">
                                                                        empty
                                                                    </span>
                                                                )}
                                                            </span>
                                                        </td>
                                                    </tr>
                                                ))}
                                            </tbody>
                                        </table>
                                    </div>
                                </Section>
                            </div>
                        )}

                        {/* Tags */}
                        {log.tags.length > 0 && (
                            <div className="border-border bg-card rounded-xl border p-5">
                                <Section title="Tags" icon={Tag}>
                                    <div className="flex flex-wrap gap-2">
                                        {log.tags.map((t, i) => (
                                            <span
                                                key={i}
                                                className="border-border bg-muted/40 rounded-full border px-2.5 py-1 font-mono text-xs"
                                            >
                                                <span className="text-muted-foreground">
                                                    {t.key}=
                                                </span>
                                                <span className="text-foreground">
                                                    {t.value}
                                                </span>
                                            </span>
                                        ))}
                                    </div>
                                </Section>
                            </div>
                        )}
                    </div>

                    {/* ── Right column: investigation ── */}
                    <div className="space-y-5">
                        {/* Respond */}
                        <div className="border-border bg-card rounded-xl border p-5">
                            <h3 className="text-foreground mb-4 text-sm font-semibold">
                                Respond to this event
                            </h3>
                            <NoteForm
                                logId={log.id}
                                onSuccess={handleNoteSuccess}
                            />
                        </div>

                        {/* Investigation timeline */}
                        <div className="border-border bg-card rounded-xl border p-5">
                            <h3 className="text-foreground mb-4 text-sm font-semibold">
                                Investigation history
                                {notes.length > 0 && (
                                    <span className="bg-muted text-muted-foreground ml-2 rounded-full px-2 py-0.5 text-xs font-normal">
                                        {notes.length}
                                    </span>
                                )}
                            </h3>

                            {notes.length === 0 ? (
                                <div className="py-8 text-center">
                                    <Clock className="text-muted-foreground dark:text-muted-foreground/30 mx-auto h-8 w-8" />
                                    <p className="text-muted-foreground mt-2 text-xs">
                                        No responses yet
                                    </p>
                                </div>
                            ) : (
                                <div className="space-y-3">
                                    {notes.map((note, i) => {
                                        const cfg =
                                            NOTE_CONFIG[note.type] ??
                                            NOTE_CONFIG.note;
                                        const Icon = cfg.icon;
                                        return (
                                            <div
                                                key={note.id}
                                                className="relative pl-6"
                                            >
                                                {/* Timeline line */}
                                                {i < notes.length - 1 && (
                                                    <div className="bg-border absolute top-6 left-[9px] h-full w-px" />
                                                )}
                                                {/* Timeline dot */}
                                                <div
                                                    className={cn(
                                                        'absolute top-1.5 left-0 flex h-4.5 w-4.5 items-center justify-center rounded-full border',
                                                        cfg.color,
                                                    )}
                                                >
                                                    <Icon className="h-2.5 w-2.5" />
                                                </div>
                                                <div
                                                    className={cn(
                                                        'rounded-lg border p-3',
                                                        cfg.color,
                                                    )}
                                                >
                                                    <div className="flex items-center justify-between gap-2">
                                                        <span className="text-xs font-semibold">
                                                            {note.admin_name}
                                                        </span>
                                                        <span className="text-muted-foreground text-[10px]">
                                                            {cfg.label} ·{' '}
                                                            {formatDistanceToNow(
                                                                parseServerDate(
                                                                    note.created_at,
                                                                ),
                                                                {
                                                                    addSuffix: true,
                                                                },
                                                            )}
                                                        </span>
                                                    </div>
                                                    {note.body && (
                                                        <p className="mt-1.5 text-xs leading-relaxed">
                                                            {note.body}
                                                        </p>
                                                    )}
                                                </div>
                                            </div>
                                        );
                                    })}
                                </div>
                            )}
                        </div>
                    </div>
                </div>
            </div>
        </AdminLayout>
    );
}
