import { useState, useEffect } from 'react';
import {
    Shield, Search, Filter, Download,
    LogIn, LogOut, Edit, Trash2, FileDown, ThumbsUp, ThumbsDown,
    Eye, Clock, User, ShieldCheck, Activity, Terminal, AlertTriangle,
    X, ArrowRight
} from 'lucide-react';
import { auditApi, AuditLog, AuditLogSummary, AuditLogFilters } from '../lib/auditApi';
import { DataTable, Column } from '../components/ui/DataTable';
import { Card } from '../components/ui/card';
import { cn } from '../lib/utils';
import { motion, AnimatePresence } from 'framer-motion';

// --- Configuration ---

const ACTION_CONFIG: Record<string, { icon: any; color: string; label: string }> = {
    CREATE: { icon: ThumbsUp, color: 'text-[var(--color-primary)] bg-[var(--color-primary)]/10 border-emerald-500/20', label: 'Create' },
    UPDATE: { icon: Edit, color: 'text-[var(--color-accent)] bg-[var(--color-accent)]/10 border-blue-500/20', label: 'Update' },
    DELETE: { icon: Trash2, color: 'text-[var(--color-error)] bg-[var(--color-error)]/10 border-rose-500/20', label: 'Delete' },
    LOGIN: { icon: LogIn, color: 'text-cyan-500 bg-cyan-500/10 border-cyan-500/20', label: 'Login' },
    LOGOUT: { icon: LogOut, color: 'text-[var(--color-text-tertiary)] bg-slate-500/10 border-slate-500/20', label: 'Logout' },
    ACCESS: { icon: Eye, color: 'text-indigo-500 bg-indigo-500/10 border-indigo-500/20', label: 'Access' },
    EXPORT: { icon: FileDown, color: 'text-[var(--color-warning)] bg-[var(--color-warning)]/10 border-amber-500/20', label: 'Export' },
    APPROVE: { icon: ThumbsUp, color: 'text-[var(--color-primary)] bg-[var(--color-primary)]/10 border-emerald-500/20', label: 'Approve' },
    REJECT: { icon: ThumbsDown, color: 'text-[var(--color-error)] bg-[var(--color-error)]/10 border-rose-500/20', label: 'Reject' }
};

const ENTITY_LABELS: Record<string, string> = {
    Batch: 'Batch', Room: 'Room', Task: 'Task', User: 'User',
    Visitor: 'Visitor', Document: 'Document', AuditLog: 'Audit Log',
    Plant: 'Plant', Supply: 'Supply'
};

export default function AuditLogPage() {
    const [logs, setLogs] = useState<AuditLog[]>([]);
    const [summary, setSummary] = useState<AuditLogSummary | null>(null);
    const [loading, setLoading] = useState(true);
    const [exporting, setExporting] = useState(false);
    const [selectedLog, setSelectedLog] = useState<AuditLog | null>(null);

    const [filters, setFilters] = useState<AuditLogFilters>({ page: 1, limit: 25 });
    const [pagination, setPagination] = useState({ page: 1, limit: 25, total: 0, pages: 0 });

    useEffect(() => {
        loadData();
    }, [filters]);

    async function loadData() {
        setLoading(true);
        try {
            const [logsData, summaryData] = await Promise.all([
                auditApi.getLogs(filters),
                auditApi.getSummary()
            ]);
            setLogs(logsData.logs);
            setPagination(logsData.pagination);
            setSummary(summaryData);
        } catch (error) {
            console.error('Failed to load audit logs:', error);
        } finally {
            setLoading(false);
        }
    }

    async function handleExport() {
        setExporting(true);
        try {
            const blob = await auditApi.exportCsv({
                entity: filters.entity,
                startDate: filters.startDate,
                endDate: filters.endDate
            });
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `audit-log-${new Date().toISOString().split('T')[0]}.csv`;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            window.URL.revokeObjectURL(url);
        } catch (error) {
            console.error('Export failed:', error);
        } finally {
            setExporting(false);
        }
    }

    const columns: Column<AuditLog>[] = [
        {
            key: 'timestamp',
            header: 'Timestamp',
            cell: (log) => (
                <div className="flex flex-col">
                    <span className="text-xs font-extra-bold text-[var(--color-text-primary)] font-mono tracking-tight">
                        {new Date(log.timestamp).toLocaleTimeString([], { hour12: false, hour: '2-digit', minute: '2-digit', second: '2-digit' })}
                    </span>
                    <span className="text-[10px] text-[var(--color-text-tertiary)] font-bold uppercase tracking-tighter">
                        {new Date(log.timestamp).toLocaleDateString()}
                    </span>
                </div>
            )
        },
        {
            key: 'userName',
            header: 'Identity',
            cell: (log) => (
                <div className="flex items-center gap-2">
                    <div className="w-5 h-5 rounded bg-slate-100 dark:bg-slate-800 flex items-center justify-center border border-[var(--color-border-subtle)]">
                        <User size={10} className="text-[var(--color-text-tertiary)]" />
                    </div>
                    <span className="text-xs font-bold text-[var(--color-text-secondary)] uppercase tracking-widest">
                        {log.userName || 'SYSTEM_CORE'}
                    </span>
                </div>
            )
        },
        {
            key: 'action',
            header: 'Operation',
            cell: (log) => {
                const config = ACTION_CONFIG[log.action] || { icon: Shield, color: 'text-[var(--color-text-tertiary)] bg-slate-100 border-slate-200', label: log.action };
                const Icon = config.icon;
                return (
                    <div className={cn(
                        "inline-flex items-center gap-1.5 px-2 py-0.5 rounded border text-[9px] font-black uppercase tracking-[0.15em]",
                        config.color
                    )}>
                        <Icon size={10} />
                        {config.label}
                    </div>
                );
            }
        },
        {
            key: 'entity',
            header: 'Resource',
            cell: (log) => (
                <div className="flex flex-col">
                    <span className="text-xs font-bold text-[var(--color-text-primary)] uppercase italic tracking-tight">
                        {ENTITY_LABELS[log.entity] || log.entity}
                    </span>
                    {log.entityName && (
                        <span className="text-[9px] text-[var(--color-text-tertiary)] font-medium truncate max-w-[150px] uppercase">
                            ID: {log.entityName}
                        </span>
                    )}
                </div>
            )
        },
        {
            key: 'details',
            header: 'Event Summary',
            hideOnMobile: true,
            cell: (log) => (
                <span className="text-[11px] text-[var(--color-text-tertiary)] font-medium truncate max-w-[250px] block">
                    {log.changes ? `MODIFIED: ${Object.keys(log.changes).join(', ')}` :
                        log.ipAddress ? `IP_SRC: ${log.ipAddress}` : 'No additional metadata'}
                </span>
            )
        }
    ];

    return (
        <div className="space-y-8 pb-12">
            {/* Header section */}
            <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
                <div className="space-y-1">
                    <h1 className="text-3xl font-extra-bold tracking-tight text-[var(--color-text-primary)] uppercase italic">
                        System Ledger
                    </h1>
                    <div className="flex items-center gap-2 text-[var(--color-text-tertiary)] text-xs font-bold uppercase tracking-widest">
                        <ShieldCheck size={14} className="text-[var(--color-accent)]" />
                        <span>High-fidelity audit trail • Compliant with Title 21 CFR Part 11</span>
                    </div>
                </div>

                <div className="flex items-center gap-2">
                    <button
                        onClick={handleExport}
                        disabled={exporting}
                        className="flex items-center gap-2 bg-slate-900 dark:bg-white text-white dark:text-black px-4 py-2 rounded-lg font-bold text-xs shadow-xl transition-all uppercase tracking-widest hover:scale-[1.02]"
                    >
                        <Download size={16} />
                        {exporting ? 'Generating...' : 'Export Audit CSV'}
                    </button>
                </div>
            </div>

            {/* Metrics Grid */}
            {summary && (
                <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
                    <MetricMini label="Total Entries" value={summary.totalLogs.toLocaleString()} icon={Terminal} color="blue" />
                    <MetricMini label="Critical Deletes" value={summary.byAction['DELETE'] || 0} icon={AlertTriangle} color="rose" />
                    <MetricMini label="Record Updates" value={summary.byAction['UPDATE'] || 0} icon={Activity} color="emerald" />
                    <MetricMini label="Security Events" value={summary.byAction['LOGIN'] || 0} icon={Shield} color="indigo" />
                </div>
            )}

            {/* Main Ledger Table */}
            <div className="space-y-4">
                <DataTable
                    data={logs}
                    columns={columns}
                    isLoading={loading}
                    onRowClick={(log) => setSelectedLog(log)}
                />

                {/* Simplified Clinical Pagination */}
                <div className="flex items-center justify-between px-2 pt-4 border-t border-[var(--color-border-subtle)]">
                    <p className="text-[10px] font-bold text-[var(--color-text-tertiary)] uppercase tracking-widest">
                        Index <span className="text-[var(--color-text-primary)]">{((pagination.page - 1) * pagination.limit) + 1}–{Math.min(pagination.page * pagination.limit, pagination.total)}</span> / {pagination.total} RECORDED_EVENTS
                    </p>
                    <div className="flex gap-1.5 font-mono">
                        <button
                            onClick={() => setFilters({ ...filters, page: pagination.page - 1 })}
                            disabled={pagination.page <= 1}
                            className="p-2 rounded border border-[var(--color-border-subtle)] disabled:opacity-30 hover:bg-slate-50 dark:hover:bg-slate-900 transition-colors"
                        >
                            <Terminal size={14} className="rotate-180" />
                        </button>
                        <div className="flex items-center px-4 text-xs font-black text-[var(--color-text-primary)] bg-slate-100 dark:bg-slate-800 rounded border border-[var(--color-border-subtle)]">
                            {pagination.page} / {pagination.pages}
                        </div>
                        <button
                            onClick={() => setFilters({ ...filters, page: pagination.page + 1 })}
                            disabled={pagination.page >= pagination.pages}
                            className="p-2 rounded border border-[var(--color-border-subtle)] disabled:opacity-30 hover:bg-slate-50 dark:hover:bg-slate-900 transition-colors"
                        >
                            <Terminal size={14} />
                        </button>
                    </div>
                </div>
            </div>

            {/* High-Trust Detail Modal */}
            <AnimatePresence>
                {selectedLog && (
                    <motion.div
                        initial={{ opacity: 0 }}
                        animate={{ opacity: 1 }}
                        exit={{ opacity: 0 }}
                        className="fixed inset-0 bg-slate-950/80 backdrop-blur-md flex items-center justify-center p-4 z-[100]"
                        onClick={() => setSelectedLog(null)}
                    >
                        <motion.div
                            initial={{ scale: 0.95, y: 20 }}
                            animate={{ scale: 1, y: 0 }}
                            exit={{ scale: 0.95, y: 20 }}
                            className="bg-[#0B0E14] border border-slate-800 rounded-2xl shadow-[0_0_50px_rgba(0,0,0,0.5)] max-w-3xl w-full max-h-[90vh] overflow-hidden flex flex-col"
                            onClick={e => e.stopPropagation()}
                        >
                            {/* Modal Header */}
                            <div className="p-6 border-b border-slate-800 flex justify-between items-center bg-slate-900/40">
                                <div>
                                    <div className="flex items-center gap-2 mb-1">
                                        <Terminal size={14} className="text-[var(--color-accent)]" />
                                        <h3 className="text-xs font-black text-[var(--color-text-tertiary)] uppercase tracking-[0.2em]">Transaction_Inspector</h3>
                                    </div>
                                    <h3 className="text-xl font-extra-bold text-white uppercase italic tracking-tight">Record Object Detail</h3>
                                </div>
                                <button onClick={() => setSelectedLog(null)} className="p-2 text-[var(--color-text-tertiary)] hover:text-white transition-colors">
                                    <X size={20} />
                                </button>
                            </div>

                            {/* Modal Content */}
                            <div className="p-8 overflow-y-auto space-y-8">
                                {/* Metadata Strip */}
                                <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                                    <ModalMeta label="Record ID" value={selectedLog.id.substring(0, 12)} />
                                    <ModalMeta label="Timestamp" value={new Date(selectedLog.timestamp).toLocaleTimeString([], { hour12: false })} />
                                    <ModalMeta label="Identity" value={selectedLog.userName || 'SYSTEM'} />
                                    <ModalMeta label="Source IP" value={selectedLog.ipAddress || 'INTERNAL'} />
                                </div>

                                {/* Property Diff Visualization */}
                                <div className="space-y-4">
                                    <div className="flex items-center justify-between">
                                        <h4 className="text-[10px] font-black text-[var(--color-text-tertiary)] uppercase tracking-widest border-l-2 border-emerald-500 pl-2">State Transition Map</h4>
                                    </div>

                                    {selectedLog.changes && Object.keys(selectedLog.changes).length > 0 ? (
                                        <div className="space-y-3">
                                            {Object.entries(selectedLog.changes).map(([key, val]: [string, any]) => (
                                                <div key={key} className="p-4 bg-slate-900/50 rounded-xl border border-slate-800/50">
                                                    <div className="text-[10px] font-black text-[var(--color-text-tertiary)] mb-3 uppercase tracking-widest italic">{key}</div>
                                                    <div className="grid grid-cols-1 md:grid-cols-[1fr,24px,1fr] items-center gap-4">
                                                        <div className="p-3 bg-[var(--color-error)]/5 border border-rose-500/10 rounded font-mono text-xs text-[var(--color-error)]/80 whitespace-pre-wrap break-all">
                                                            <div className="text-[8px] uppercase font-bold text-[var(--color-error)]/50 mb-1">Previous_State</div>
                                                            {JSON.stringify(val.from, null, 2)}
                                                        </div>
                                                        <ArrowRight size={14} className="text-slate-700 mx-auto" />
                                                        <div className="p-3 bg-[var(--color-primary)]/5 border border-emerald-500/10 rounded font-mono text-xs text-[var(--color-primary)] whitespace-pre-wrap break-all">
                                                            <div className="text-[8px] uppercase font-bold text-[var(--color-primary)]/50 mb-1">Committed_State</div>
                                                            {JSON.stringify(val.to, null, 2)}
                                                        </div>
                                                    </div>
                                                </div>
                                            ))}
                                        </div>
                                    ) : (
                                        <div className="py-12 text-center bg-slate-900/30 rounded-2xl border border-dashed border-slate-800 flex flex-col items-center gap-3">
                                            <Activity className="text-slate-700" size={32} />
                                            <p className="text-xs font-bold text-slate-600 uppercase tracking-widest">No state modifications recorded.</p>
                                        </div>
                                    )}
                                </div>
                            </div>

                            {/* Modal Footer */}
                            <div className="p-4 bg-slate-900/60 border-t border-slate-800 flex justify-end">
                                <button className="text-[10px] font-black text-[var(--color-text-tertiary)] uppercase tracking-widest hover:text-[var(--color-primary)] transition-colors flex items-center gap-2">
                                    Verify with Blockchain Ledger <Shield size={12} />
                                </button>
                            </div>
                        </motion.div>
                    </motion.div>
                )}
            </AnimatePresence>
        </div>
    );
}

function MetricMini({ label, value, icon: Icon, color }: any) {
    const colorClasses: Record<string, string> = {
        blue: 'text-[var(--color-accent)] bg-[var(--color-accent)]/5 border-blue-500/10',
        rose: 'text-[var(--color-error)] bg-[var(--color-error)]/5 border-rose-500/10',
        emerald: 'text-[var(--color-primary)] bg-[var(--color-primary)]/5 border-emerald-500/10',
        indigo: 'text-indigo-500 bg-indigo-500/5 border-indigo-500/10'
    };

    return (
        <Card className="p-4 bg-[var(--color-bg-elevated)] border-[var(--color-border-subtle)] flex items-center justify-between group">
            <div className="space-y-1">
                <p className="text-[9px] font-black text-[var(--color-text-tertiary)] uppercase tracking-widest">{label}</p>
                <div className="text-xl font-black italic tracking-tighter text-[var(--color-text-primary)]">{value}</div>
            </div>
            <div className={cn("p-2.5 rounded-lg border", colorClasses[color])}>
                <Icon size={16} />
            </div>
        </Card>
    );
}

function ModalMeta({ label, value }: any) {
    return (
        <div className="space-y-1">
            <p className="text-[9px] font-black text-[var(--color-text-tertiary)] uppercase tracking-widest">{label}</p>
            <p className="text-xs font-bold text-white font-mono">{value}</p>
        </div>
    );
}

