"use client";

import { X, Clock, User, Shield, Target, FileJson, AlertCircle, Copy, Check, Activity } from "lucide-react";
import { format } from "date-fns";
import { useState } from "react";
import type { AuditLog } from "./AdminActivityLogsDashboard";

interface Props {
    log: AuditLog;
    onClose: () => void;
}

export default function DetailedLogModal({ log, onClose }: Props) {
    const [copied, setCopied] = useState(false);

    const handleCopy = (text: string) => {
        navigator.clipboard.writeText(text);
        setCopied(true);
        setTimeout(() => setCopied(false), 2000);
    };

    const detailsObj = typeof log.details === 'string'
        ? JSON.parse(log.details || "{}")
        : (log.details || {});

    const severity = detailsObj.severity || 'INFO';
    const category = detailsObj.category || 'SYSTEM';

    return (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 sm:p-6">
            <div
                className="absolute inset-0 bg-slate-900/60 backdrop-blur-sm transition-opacity"
                onClick={onClose}
            />

            <div className="relative bg-white rounded-2xl shadow-xl w-full max-w-4xl max-h-[90vh] flex flex-col overflow-hidden animate-in fade-in zoom-in-95 duration-200">

                {/* Header */}
                <div className="flex items-center justify-between px-6 py-4 border-b border-slate-200 bg-slate-50">
                    <div>
                        <div className="flex items-center gap-3">
                            <h2 className="text-lg font-bold text-slate-800">Log Event Details</h2>
                            <span className={`px-2 py-0.5 rounded text-xs font-bold font-mono tracking-wide
                                ${severity === 'CRITICAL' ? 'bg-neutral-900 text-white' :
                                    severity === 'ERROR' ? 'bg-red-100 text-red-700' :
                                        severity === 'WARNING' ? 'bg-amber-100 text-amber-700' :
                                            severity === 'SUCCESS' ? 'bg-emerald-100 text-emerald-700' :
                                                'bg-blue-100 text-blue-700'}
                            `}>
                                {severity}
                            </span>
                        </div>
                        <p className="text-xs text-slate-500 mt-1 font-mono">
                            ID: {log.id} • {category}
                        </p>
                    </div>
                    <div className="flex items-center gap-2">
                        <button
                            onClick={() => handleCopy(JSON.stringify(log, null, 2))}
                            className="p-2 text-slate-500 hover:text-slate-700 hover:bg-slate-200 rounded-lg transition-colors flex items-center gap-2 text-sm font-medium"
                        >
                            {copied ? <Check className="w-4 h-4 text-emerald-500" /> : <Copy className="w-4 h-4" />}
                            {copied ? "Copied JSON" : "Export JSON"}
                        </button>
                        <button
                            onClick={onClose}
                            className="p-2 text-slate-500 hover:text-slate-800 hover:bg-slate-200 rounded-lg transition-colors"
                        >
                            <X className="w-5 h-5" />
                        </button>
                    </div>
                </div>

                {/* Body */}
                <div className="overflow-y-auto p-6 flex-1 bg-slate-50/50">
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">

                        {/* Left Column: Context */}
                        <div className="space-y-6">

                            {/* Action Summary */}
                            <div className="bg-white border border-slate-200 rounded-xl p-5 shadow-sm">
                                <h3 className="text-sm font-bold text-slate-800 mb-4 flex items-center gap-2">
                                    <Activity className="w-4 h-4 text-blue-500" />
                                    Action Summary
                                </h3>
                                <div className="space-y-3">
                                    <div className="flex justify-between border-b border-slate-100 pb-2">
                                        <span className="text-xs text-slate-500 uppercase tracking-wider">Event Type</span>
                                        <span className="text-sm font-semibold text-slate-800 bg-slate-100 px-2 py-0.5 rounded font-mono">{log.action.toUpperCase()}</span>
                                    </div>
                                    <div className="flex justify-between border-b border-slate-100 pb-2">
                                        <span className="text-xs text-slate-500 uppercase tracking-wider">Timestamp (UTC)</span>
                                        <span className="text-sm font-medium text-slate-700">{format(new Date(log.created_at), "yyyy-MM-dd HH:mm:ss")}</span>
                                    </div>
                                    <div className="flex justify-between pb-2">
                                        <span className="text-xs text-slate-500 uppercase tracking-wider">Client IP</span>
                                        <span className="text-sm font-mono text-slate-600">{log.ip_address || "Unknown"}</span>
                                    </div>
                                </div>
                            </div>

                            {/* Actor Info */}
                            <div className="bg-white border border-slate-200 rounded-xl p-5 shadow-sm">
                                <h3 className="text-sm font-bold text-slate-800 mb-4 flex items-center gap-2">
                                    <User className="w-4 h-4 text-indigo-500" />
                                    Actor details
                                </h3>
                                {log.user ? (
                                    <div className="flex items-start gap-4">
                                        <div className="w-10 h-10 rounded-full bg-slate-100 border border-slate-200 flex items-center justify-center font-bold text-slate-600 uppercase">
                                            {log.user.name?.[0] || log.user.email?.[0] || "?"}
                                        </div>
                                        <div>
                                            <p className="text-sm font-bold text-slate-900">{log.user.name || "Unknown Name"}</p>
                                            <p className="text-xs text-slate-500">{log.user.email}</p>
                                            <div className="mt-2 text-xs font-medium px-2 py-0.5 bg-indigo-50 text-indigo-600 border border-indigo-100 rounded-md inline-block">
                                                {log.user.role.toUpperCase()}
                                            </div>
                                        </div>
                                    </div>
                                ) : (
                                    <div className="flex items-center gap-3 text-slate-500">
                                        <Shield className="w-8 h-8 opacity-50" />
                                        <div>
                                            <p className="text-sm font-bold">SYSTEM</p>
                                            <p className="text-xs">Automated action</p>
                                        </div>
                                    </div>
                                )}
                            </div>

                            {/* Target Info */}
                            <div className="bg-white border border-slate-200 rounded-xl p-5 shadow-sm">
                                <h3 className="text-sm font-bold text-slate-800 mb-4 flex items-center gap-2">
                                    <Target className="w-4 h-4 text-emerald-500" />
                                    Target Resource
                                </h3>
                                {log.resource_id ? (
                                    <div className="space-y-3">
                                        <div className="flex justify-between border-b border-slate-100 pb-2">
                                            <span className="text-xs text-slate-500 uppercase tracking-wider">Type</span>
                                            <span className="text-sm font-medium text-slate-700 capitalize">{log.resource_type || "Unknown"}</span>
                                        </div>
                                        <div className="flex justify-between">
                                            <span className="text-xs text-slate-500 uppercase tracking-wider">ID</span>
                                            <span className="text-xs font-mono bg-slate-100 px-2 py-1 rounded border border-slate-200 select-all">
                                                {log.resource_id}
                                            </span>
                                        </div>
                                    </div>
                                ) : (
                                    <div className="text-center py-4 text-sm text-slate-500 italic">
                                        No specific resource targeted
                                    </div>
                                )}
                            </div>
                        </div>

                        {/* Right Column: Payload Data */}
                        <div className="space-y-6">

                            {/* Rich Details Render */}
                            <div className="bg-white border border-slate-200 rounded-xl shadow-sm overflow-hidden flex flex-col h-full">
                                <div className="p-4 border-b border-slate-100 bg-slate-50 flex items-center justify-between">
                                    <h3 className="text-sm font-bold text-slate-800 flex items-center gap-2">
                                        <FileJson className="w-4 h-4 text-amber-500" />
                                        Execution Details
                                    </h3>
                                </div>
                                <div className="p-0 flex-1 bg-slate-900 overflow-hidden rounded-b-xl relative group">
                                    <div className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity">
                                        <button
                                            onClick={() => handleCopy(JSON.stringify(detailsObj, null, 2))}
                                            className="p-1.5 bg-slate-800 hover:bg-slate-700 text-slate-300 rounded border border-slate-700"
                                            title="Copy Details Payload"
                                        >
                                            {copied ? <Check className="w-3.5 h-3.5" /> : <Copy className="w-3.5 h-3.5" />}
                                        </button>
                                    </div>
                                    <pre className="p-4 text-xs font-mono text-emerald-400 overflow-x-auto whitespace-pre-wrap leading-relaxed h-full max-h-[500px]">
                                        {JSON.stringify(detailsObj, null, 2)}
                                    </pre>
                                </div>
                            </div>

                        </div>
                    </div>
                </div>

                {/* Footer */}
                <div className="px-6 py-4 border-t border-slate-200 bg-slate-50 flex justify-end">
                    <button
                        onClick={onClose}
                        className="px-5 py-2 bg-white border border-slate-300 text-slate-700 rounded-lg hover:bg-slate-50 font-medium transition-colors shadow-sm"
                    >
                        Close Inspector
                    </button>
                </div>
            </div>
        </div>
    );
}
