import { useState, useEffect } from 'react';
import {
    Shield, Search, Filter, Download, ChevronLeft, ChevronRight,
    User, Clock, Eye, X, Loader2, FileText,
    LogIn, LogOut, Edit, Trash2, FileDown, ThumbsUp, ThumbsDown
} from 'lucide-react';
import { auditApi, AuditLog, AuditLogSummary, AuditLogFilters } from '../lib/auditApi';
import { PageHeader, MetricCard, EmptyState } from '../components/ui/LinearPrimitives';

const ACTION_CONFIG: Record<string, { icon: React.ElementType; badge: string; label: string }> = {
    CREATE: { icon: FileText, badge: 'badge-success', label: 'Created' },
    UPDATE: { icon: Edit, badge: 'badge-accent', label: 'Updated' },
    DELETE: { icon: Trash2, badge: 'badge-destructive', label: 'Deleted' },
    LOGIN: { icon: LogIn, badge: 'badge-accent', label: 'Login' },
    LOGOUT: { icon: LogOut, badge: 'badge', label: 'Logout' },
    ACCESS: { icon: Eye, badge: 'badge-accent', label: 'Accessed' },
    EXPORT: { icon: FileDown, badge: 'badge-warning', label: 'Exported' },
    APPROVE: { icon: ThumbsUp, badge: 'badge-success', label: 'Approved' },
    REJECT: { icon: ThumbsDown, badge: 'badge-destructive', label: 'Rejected' }
};

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 [showFilters, setShowFilters] = useState(false);
    const [searchTerm, setSearchTerm] = useState('');
    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);
        }
    }

    function formatTimestamp(ts: string) {
        const date = new Date(ts);
        const now = new Date();
        const diffMs = now.getTime() - date.getTime();
        const diffMins = Math.floor(diffMs / 60000);
        const diffHours = Math.floor(diffMins / 60);
        const diffDays = Math.floor(diffHours / 24);

        if (diffMins < 1) return 'Just now';
        if (diffMins < 60) return `${diffMins}m ago`;
        if (diffHours < 24) return `${diffHours}h ago`;
        if (diffDays < 7) return `${diffDays}d ago`;
        return date.toLocaleDateString();
    }

    function getActionConfig(action: string) {
        return ACTION_CONFIG[action] || { icon: FileText, badge: 'badge', label: action };
    }

    return (
        <div className="space-y-6 pb-20 animate-in">
            <PageHeader
                title="Audit Log"
                subtitle="Complete activity trail for compliance"
                actions={
                    <div className="flex gap-2">
                        <button
                            onClick={() => setShowFilters(!showFilters)}
                            className={`btn ${showFilters ? 'btn-primary' : 'btn-secondary'}`}
                        >
                            <Filter size={16} />
                            <span className="hidden sm:inline">Filters</span>
                        </button>
                        <button
                            onClick={handleExport}
                            disabled={exporting}
                            className="btn btn-primary"
                        >
                            <Download size={16} />
                            {exporting ? 'Exporting...' : 'Export'}
                        </button>
                    </div>
                }
            />

            {/* Summary Cards */}
            {summary && (
                <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
                    <MetricCard icon={Shield} label="Total Events" value={summary.totalLogs.toLocaleString()} accent="accent" />
                    <MetricCard icon={FileText} label="Creates" value={summary.byAction['CREATE'] || 0} accent="success" />
                    <MetricCard icon={Edit} label="Updates" value={summary.byAction['UPDATE'] || 0} accent="accent" />
                    <MetricCard icon={Trash2} label="Deletes" value={summary.byAction['DELETE'] || 0} accent="destructive" />
                </div>
            )}

            {/* Filters Panel */}
            {showFilters && (
                <div className="card p-4">
                    <div className="grid grid-cols-1 md:grid-cols-4 gap-3">
                        <div className="relative">
                            <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-tertiary" size={16} />
                            <input
                                type="text"
                                placeholder="Search..."
                                value={searchTerm}
                                onChange={(e) => setSearchTerm(e.target.value)}
                                className="input w-full pl-9"
                            />
                        </div>

                        <select
                            value={filters.entity || ''}
                            onChange={(e) => setFilters({ ...filters, entity: e.target.value || undefined, page: 1 })}
                            className="input"
                        >
                            <option value="">All Entities</option>
                            {summary?.byEntity.map(e => (
                                <option key={e.entity} value={e.entity}>
                                    {ENTITY_LABELS[e.entity] || e.entity} ({e.count})
                                </option>
                            ))}
                        </select>

                        <select
                            value={filters.action || ''}
                            onChange={(e) => setFilters({ ...filters, action: e.target.value || undefined, page: 1 })}
                            className="input"
                        >
                            <option value="">All Actions</option>
                            <option value="CREATE">Create</option>
                            <option value="UPDATE">Update</option>
                            <option value="DELETE">Delete</option>
                            <option value="LOGIN">Login</option>
                            <option value="LOGOUT">Logout</option>
                        </select>

                        <div className="flex gap-2">
                            <input
                                type="date"
                                value={filters.startDate?.split('T')[0] || ''}
                                onChange={(e) => setFilters({ ...filters, startDate: e.target.value ? new Date(e.target.value).toISOString() : undefined, page: 1 })}
                                className="input flex-1 h-10 text-xs"
                            />
                            <input
                                type="date"
                                value={filters.endDate?.split('T')[0] || ''}
                                onChange={(e) => setFilters({ ...filters, endDate: e.target.value ? new Date(e.target.value).toISOString() : undefined, page: 1 })}
                                className="input flex-1 h-10 text-xs"
                            />
                        </div>
                    </div>

                    {(filters.entity || filters.action || filters.startDate || filters.endDate) && (
                        <button
                            onClick={() => setFilters({ page: 1, limit: 25 })}
                            className="mt-3 text-sm text-accent hover:underline flex items-center gap-1"
                        >
                            <X size={14} /> Clear filters
                        </button>
                    )}
                </div>
            )}

            {/* Logs Table */}
            <div className="card overflow-hidden">
                {loading ? (
                    <div className="flex items-center justify-center py-20">
                        <Loader2 className="animate-spin text-tertiary" size={24} />
                    </div>
                ) : logs.length === 0 ? (
                    <EmptyState
                        icon={Shield}
                        title="No audit logs found"
                        description="Activity will appear here as users interact with the system."
                    />
                ) : (
                    <>
                        <div className="overflow-x-auto">
                            <table className="w-full">
                                <thead className="bg-secondary border-b border-subtle">
                                    <tr>
                                        <th className="px-4 py-3 text-left text-xs font-medium text-tertiary uppercase tracking-wider">Time</th>
                                        <th className="px-4 py-3 text-left text-xs font-medium text-tertiary uppercase tracking-wider">User</th>
                                        <th className="px-4 py-3 text-left text-xs font-medium text-tertiary uppercase tracking-wider">Action</th>
                                        <th className="px-4 py-3 text-left text-xs font-medium text-tertiary uppercase tracking-wider">Entity</th>
                                        <th className="px-4 py-3 text-left text-xs font-medium text-tertiary uppercase tracking-wider">Details</th>
                                        <th className="px-4 py-3 text-center text-xs font-medium text-tertiary uppercase tracking-wider">View</th>
                                    </tr>
                                </thead>
                                <tbody className="divide-y divide-subtle">
                                    {logs.map(log => {
                                        const config = getActionConfig(log.action);
                                        return (
                                            <tr
                                                key={log.id}
                                                className="hover:bg-tertiary cursor-pointer transition-colors duration-fast"
                                                onClick={() => setSelectedLog(log)}
                                            >
                                                <td className="px-4 py-3">
                                                    <div className="flex items-center gap-2 text-xs text-secondary">
                                                        <Clock size={12} className="text-tertiary" />
                                                        <span>{formatTimestamp(log.timestamp)}</span>
                                                    </div>
                                                    <p className="text-[10px] text-tertiary mt-0.5">
                                                        {new Date(log.timestamp).toLocaleString()}
                                                    </p>
                                                </td>
                                                <td className="px-4 py-3">
                                                    <div className="flex items-center gap-2">
                                                        <div className="w-6 h-6 rounded-full bg-tertiary flex items-center justify-center">
                                                            <User size={12} className="text-tertiary" />
                                                        </div>
                                                        <span className="text-sm font-medium text-primary">
                                                            {log.userName || 'System'}
                                                        </span>
                                                    </div>
                                                </td>
                                                <td className="px-4 py-3">
                                                    <span className={`${config.badge} text-[10px]`}>
                                                        {config.label}
                                                    </span>
                                                </td>
                                                <td className="px-4 py-3">
                                                    <span className="text-sm font-medium text-primary">
                                                        {ENTITY_LABELS[log.entity] || log.entity}
                                                    </span>
                                                    {log.entityName && (
                                                        <p className="text-xs text-tertiary truncate max-w-[120px]">{log.entityName}</p>
                                                    )}
                                                </td>
                                                <td className="px-4 py-3">
                                                    <p className="text-xs text-tertiary truncate max-w-[150px]">
                                                        {log.changes ? `Changed: ${Object.keys(log.changes).join(', ')}` :
                                                            log.ipAddress ? `IP: ${log.ipAddress}` : '—'}
                                                    </p>
                                                </td>
                                                <td className="px-4 py-3 text-center">
                                                    <button className="p-1.5 rounded hover:bg-tertiary text-tertiary hover:text-primary transition-colors">
                                                        <Eye size={14} />
                                                    </button>
                                                </td>
                                            </tr>
                                        );
                                    })}
                                </tbody>
                            </table>
                        </div>

                        {/* Pagination */}
                        <div className="flex items-center justify-between px-4 py-3 border-t border-subtle">
                            <p className="text-xs text-tertiary">
                                {((pagination.page - 1) * pagination.limit) + 1}–{Math.min(pagination.page * pagination.limit, pagination.total)} of {pagination.total}
                            </p>
                            <div className="flex items-center gap-1">
                                <button
                                    onClick={() => setFilters({ ...filters, page: pagination.page - 1 })}
                                    disabled={pagination.page <= 1}
                                    className="btn btn-ghost p-2 disabled:opacity-50"
                                >
                                    <ChevronLeft size={16} />
                                </button>
                                <span className="text-xs text-secondary px-2">{pagination.page}/{pagination.pages}</span>
                                <button
                                    onClick={() => setFilters({ ...filters, page: pagination.page + 1 })}
                                    disabled={pagination.page >= pagination.pages}
                                    className="btn btn-ghost p-2 disabled:opacity-50"
                                >
                                    <ChevronRight size={16} />
                                </button>
                            </div>
                        </div>
                    </>
                )}
            </div>

            {/* Detail Modal */}
            {selectedLog && (
                <div className="fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50 animate-fade-in" onClick={() => setSelectedLog(null)}>
                    <div
                        className="card max-w-2xl w-full max-h-[80vh] overflow-hidden animate-scale-in"
                        onClick={e => e.stopPropagation()}
                    >
                        <div className="p-4 border-b border-subtle flex justify-between items-start">
                            <div>
                                <h3 className="text-lg font-semibold text-primary">Audit Log Detail</h3>
                                <p className="text-xs text-tertiary font-mono">ID: {selectedLog.id.slice(0, 8)}...</p>
                            </div>
                            <button
                                onClick={() => setSelectedLog(null)}
                                className="p-2 rounded-md hover:bg-tertiary transition-colors"
                            >
                                <X size={16} className="text-tertiary" />
                            </button>
                        </div>
                        <div className="p-4 overflow-y-auto max-h-[60vh] space-y-4">
                            <div className="grid grid-cols-2 gap-4">
                                <div>
                                    <p className="text-[10px] font-medium text-tertiary uppercase tracking-wider mb-1">Timestamp</p>
                                    <p className="text-sm text-primary">{new Date(selectedLog.timestamp).toLocaleString()}</p>
                                </div>
                                <div>
                                    <p className="text-[10px] font-medium text-tertiary uppercase tracking-wider mb-1">User</p>
                                    <p className="text-sm text-primary">{selectedLog.userName || 'System'}</p>
                                </div>
                                <div>
                                    <p className="text-[10px] font-medium text-tertiary uppercase tracking-wider mb-1">Action</p>
                                    <span className={`${getActionConfig(selectedLog.action).badge} text-[10px]`}>
                                        {getActionConfig(selectedLog.action).label}
                                    </span>
                                </div>
                                <div>
                                    <p className="text-[10px] font-medium text-tertiary uppercase tracking-wider mb-1">Entity</p>
                                    <p className="text-sm text-primary">
                                        {ENTITY_LABELS[selectedLog.entity] || selectedLog.entity}
                                        {selectedLog.entityName && <span className="text-tertiary ml-1">({selectedLog.entityName})</span>}
                                    </p>
                                </div>
                            </div>

                            {selectedLog.ipAddress && (
                                <div>
                                    <p className="text-[10px] font-medium text-tertiary uppercase tracking-wider mb-1">IP Address</p>
                                    <p className="text-sm font-mono text-primary">{selectedLog.ipAddress}</p>
                                </div>
                            )}

                            {selectedLog.changes && Object.keys(selectedLog.changes).length > 0 && (
                                <div>
                                    <p className="text-[10px] font-medium text-tertiary uppercase tracking-wider mb-2">Changes</p>
                                    <div className="bg-tertiary rounded-md p-3 space-y-2">
                                        {Object.entries(selectedLog.changes).map(([key, value]: [string, any]) => (
                                            <div key={key} className="flex items-start gap-2 text-xs">
                                                <span className="font-medium text-secondary min-w-[80px]">{key}:</span>
                                                <span className="text-destructive line-through">{JSON.stringify(value.from)}</span>
                                                <span className="text-tertiary">→</span>
                                                <span className="text-success">{JSON.stringify(value.to)}</span>
                                            </div>
                                        ))}
                                    </div>
                                </div>
                            )}

                            {(selectedLog.before || selectedLog.after) && (
                                <div className="grid grid-cols-2 gap-4">
                                    {selectedLog.before && (
                                        <div>
                                            <p className="text-[10px] font-medium text-tertiary uppercase tracking-wider mb-1">Before</p>
                                            <pre className="text-[10px] bg-destructive-muted p-2 rounded-md overflow-x-auto max-h-32 text-destructive font-mono">
                                                {JSON.stringify(selectedLog.before, null, 2)}
                                            </pre>
                                        </div>
                                    )}
                                    {selectedLog.after && (
                                        <div>
                                            <p className="text-[10px] font-medium text-tertiary uppercase tracking-wider mb-1">After</p>
                                            <pre className="text-[10px] bg-success-muted p-2 rounded-md overflow-x-auto max-h-32 text-success font-mono">
                                                {JSON.stringify(selectedLog.after, null, 2)}
                                            </pre>
                                        </div>
                                    )}
                                </div>
                            )}
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}
