import React, { useState, useEffect, useCallback } from 'react';
import { X, Loader, AlertCircle, ChevronLeft, ChevronRight, Search } from 'lucide-react';

const API_BASE = process.env.REACT_APP_API_BASE || 'http://localhost:3001/api';

const ACTION_BADGES = {
    login:              { bg: 'bg-green-100',  text: 'text-green-800' },
    logout:             { bg: 'bg-gray-100',   text: 'text-gray-800' },
    login_failed:       { bg: 'bg-red-100',    text: 'text-red-800' },
    cve_create:         { bg: 'bg-blue-100',   text: 'text-blue-800' },
    cve_update_status:  { bg: 'bg-yellow-100', text: 'text-yellow-800' },
    document_upload:    { bg: 'bg-purple-100',  text: 'text-purple-800' },
    document_delete:    { bg: 'bg-red-100',    text: 'text-red-800' },
    user_create:        { bg: 'bg-blue-100',   text: 'text-blue-800' },
    user_update:        { bg: 'bg-yellow-100', text: 'text-yellow-800' },
    user_delete:        { bg: 'bg-red-100',    text: 'text-red-800' },
    cve_edit:           { bg: 'bg-orange-100', text: 'text-orange-800' },
    cve_delete:         { bg: 'bg-red-100',    text: 'text-red-800' },
    cve_nvd_sync:       { bg: 'bg-green-100',  text: 'text-green-800' },
};

const ENTITY_TYPES = ['auth', 'cve', 'document', 'user'];

export default function AuditLog({ onClose }) {
    const [logs, setLogs] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    const [actions, setActions] = useState([]);
    const [pagination, setPagination] = useState({ page: 1, limit: 25, total: 0, totalPages: 0 });

    // Filters
    const [userFilter, setUserFilter] = useState('');
    const [actionFilter, setActionFilter] = useState('');
    const [entityTypeFilter, setEntityTypeFilter] = useState('');
    const [startDate, setStartDate] = useState('');
    const [endDate, setEndDate] = useState('');

    const fetchLogs = useCallback(async (page = 1) => {
        setLoading(true);
        setError(null);
        try {
            const params = new URLSearchParams({ page, limit: 25 });
            if (userFilter) params.append('user', userFilter);
            if (actionFilter) params.append('action', actionFilter);
            if (entityTypeFilter) params.append('entityType', entityTypeFilter);
            if (startDate) params.append('startDate', startDate);
            if (endDate) params.append('endDate', endDate);

            const response = await fetch(`${API_BASE}/audit-logs?${params}`, {
                credentials: 'include'
            });
            if (!response.ok) throw new Error('Failed to fetch audit logs');
            const data = await response.json();
            setLogs(data.logs);
            setPagination(data.pagination);
        } catch (err) {
            setError(err.message);
        } finally {
            setLoading(false);
        }
    }, [userFilter, actionFilter, entityTypeFilter, startDate, endDate]);

    const fetchActions = async () => {
        try {
            const response = await fetch(`${API_BASE}/audit-logs/actions`, {
                credentials: 'include'
            });
            if (response.ok) {
                const data = await response.json();
                setActions(data);
            }
        } catch (err) {
            // Non-critical, ignore
        }
    };

    useEffect(() => {
        fetchLogs(1);
        fetchActions();
    }, [fetchLogs]);

    const formatDate = (dateStr) => {
        if (!dateStr) return '-';
        return new Date(dateStr).toLocaleString();
    };

    const formatDetails = (details) => {
        if (!details) return '-';
        try {
            const parsed = typeof details === 'string' ? JSON.parse(details) : details;
            return Object.entries(parsed)
                .map(([k, v]) => `${k}: ${v}`)
                .join(', ');
        } catch {
            return details;
        }
    };

    const getActionBadge = (action) => {
        const style = ACTION_BADGES[action] || { bg: 'bg-gray-100', text: 'text-gray-800' };
        return (
            <span className={`px-2 py-1 rounded text-xs font-medium ${style.bg} ${style.text}`}>
                {action}
            </span>
        );
    };

    const handleFilter = (e) => {
        e.preventDefault();
        fetchLogs(1);
    };

    const handleReset = () => {
        setUserFilter('');
        setActionFilter('');
        setEntityTypeFilter('');
        setStartDate('');
        setEndDate('');
    };

    return (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
            <div className="bg-white rounded-lg shadow-xl max-w-6xl w-full max-h-[90vh] overflow-hidden flex flex-col">
                {/* Header */}
                <div className="p-6 border-b border-gray-200 flex justify-between items-center">
                    <div>
                        <h2 className="text-2xl font-bold text-gray-900">Audit Log</h2>
                        <p className="text-gray-600">Track all user actions across the system</p>
                    </div>
                    <button
                        onClick={onClose}
                        className="text-gray-400 hover:text-gray-600 p-2"
                    >
                        <X className="w-6 h-6" />
                    </button>
                </div>

                {/* Filter Bar */}
                <form onSubmit={handleFilter} className="p-4 border-b border-gray-200 bg-gray-50">
                    <div className="grid grid-cols-2 md:grid-cols-5 gap-3">
                        <div>
                            <label className="block text-xs font-medium text-gray-600 mb-1">Username</label>
                            <div className="relative">
                                <Search className="w-4 h-4 text-gray-400 absolute left-2 top-1/2 transform -translate-y-1/2" />
                                <input
                                    type="text"
                                    placeholder="Search user..."
                                    value={userFilter}
                                    onChange={(e) => setUserFilter(e.target.value)}
                                    className="w-full pl-8 pr-3 py-1.5 text-sm border border-gray-300 rounded focus:ring-2 focus:ring-[#0476D9] focus:border-transparent"
                                />
                            </div>
                        </div>
                        <div>
                            <label className="block text-xs font-medium text-gray-600 mb-1">Action</label>
                            <select
                                value={actionFilter}
                                onChange={(e) => setActionFilter(e.target.value)}
                                className="w-full px-3 py-1.5 text-sm border border-gray-300 rounded focus:ring-2 focus:ring-[#0476D9] focus:border-transparent"
                            >
                                <option value="">All Actions</option>
                                {actions.map(a => (
                                    <option key={a} value={a}>{a}</option>
                                ))}
                            </select>
                        </div>
                        <div>
                            <label className="block text-xs font-medium text-gray-600 mb-1">Entity Type</label>
                            <select
                                value={entityTypeFilter}
                                onChange={(e) => setEntityTypeFilter(e.target.value)}
                                className="w-full px-3 py-1.5 text-sm border border-gray-300 rounded focus:ring-2 focus:ring-[#0476D9] focus:border-transparent"
                            >
                                <option value="">All Types</option>
                                {ENTITY_TYPES.map(t => (
                                    <option key={t} value={t}>{t}</option>
                                ))}
                            </select>
                        </div>
                        <div>
                            <label className="block text-xs font-medium text-gray-600 mb-1">Start Date</label>
                            <input
                                type="date"
                                value={startDate}
                                onChange={(e) => setStartDate(e.target.value)}
                                className="w-full px-3 py-1.5 text-sm border border-gray-300 rounded focus:ring-2 focus:ring-[#0476D9] focus:border-transparent"
                            />
                        </div>
                        <div>
                            <label className="block text-xs font-medium text-gray-600 mb-1">End Date</label>
                            <input
                                type="date"
                                value={endDate}
                                onChange={(e) => setEndDate(e.target.value)}
                                className="w-full px-3 py-1.5 text-sm border border-gray-300 rounded focus:ring-2 focus:ring-[#0476D9] focus:border-transparent"
                            />
                        </div>
                    </div>
                    <div className="flex gap-2 mt-3">
                        <button
                            type="submit"
                            className="px-4 py-1.5 text-sm bg-[#0476D9] text-white rounded hover:bg-[#0360B8] transition-colors"
                        >
                            Apply Filters
                        </button>
                        <button
                            type="button"
                            onClick={handleReset}
                            className="px-4 py-1.5 text-sm bg-gray-200 text-gray-700 rounded hover:bg-gray-300 transition-colors"
                        >
                            Reset
                        </button>
                    </div>
                </form>

                {/* Content */}
                <div className="p-4 overflow-y-auto flex-1">
                    {loading ? (
                        <div className="text-center py-12">
                            <Loader className="w-8 h-8 text-[#0476D9] mx-auto animate-spin" />
                            <p className="text-gray-600 mt-2">Loading audit logs...</p>
                        </div>
                    ) : error ? (
                        <div className="text-center py-12">
                            <AlertCircle className="w-8 h-8 text-red-500 mx-auto" />
                            <p className="text-red-600 mt-2">{error}</p>
                        </div>
                    ) : logs.length === 0 ? (
                        <div className="text-center py-12">
                            <p className="text-gray-500">No audit log entries found.</p>
                        </div>
                    ) : (
                        <div className="overflow-x-auto">
                            <table className="w-full text-sm">
                                <thead>
                                    <tr className="border-b border-gray-200">
                                        <th className="text-left py-2 px-3 text-xs font-medium text-gray-600">Time</th>
                                        <th className="text-left py-2 px-3 text-xs font-medium text-gray-600">User</th>
                                        <th className="text-left py-2 px-3 text-xs font-medium text-gray-600">Action</th>
                                        <th className="text-left py-2 px-3 text-xs font-medium text-gray-600">Entity</th>
                                        <th className="text-left py-2 px-3 text-xs font-medium text-gray-600">Details</th>
                                        <th className="text-left py-2 px-3 text-xs font-medium text-gray-600">IP Address</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {logs.map((log) => (
                                        <tr key={log.id} className="border-b border-gray-100 hover:bg-gray-50">
                                            <td className="py-2 px-3 text-gray-600 whitespace-nowrap">
                                                {formatDate(log.created_at)}
                                            </td>
                                            <td className="py-2 px-3 font-medium text-gray-900">
                                                {log.username}
                                            </td>
                                            <td className="py-2 px-3">
                                                {getActionBadge(log.action)}
                                            </td>
                                            <td className="py-2 px-3 text-gray-700">
                                                <span className="text-gray-500">{log.entity_type}</span>
                                                {log.entity_id && (
                                                    <span className="ml-1 text-gray-900">{log.entity_id}</span>
                                                )}
                                            </td>
                                            <td className="py-2 px-3 text-gray-600 max-w-xs truncate" title={formatDetails(log.details)}>
                                                {formatDetails(log.details)}
                                            </td>
                                            <td className="py-2 px-3 text-gray-500 font-mono text-xs">
                                                {log.ip_address || '-'}
                                            </td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        </div>
                    )}
                </div>

                {/* Pagination */}
                {pagination.totalPages > 1 && (
                    <div className="p-4 border-t border-gray-200 flex items-center justify-between">
                        <p className="text-sm text-gray-600">
                            Showing {((pagination.page - 1) * pagination.limit) + 1} - {Math.min(pagination.page * pagination.limit, pagination.total)} of {pagination.total} entries
                        </p>
                        <div className="flex items-center gap-2">
                            <button
                                onClick={() => fetchLogs(pagination.page - 1)}
                                disabled={pagination.page <= 1}
                                className="p-2 rounded hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed"
                            >
                                <ChevronLeft className="w-4 h-4" />
                            </button>
                            <span className="text-sm text-gray-700">
                                Page {pagination.page} of {pagination.totalPages}
                            </span>
                            <button
                                onClick={() => fetchLogs(pagination.page + 1)}
                                disabled={pagination.page >= pagination.totalPages}
                                className="p-2 rounded hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed"
                            >
                                <ChevronRight className="w-4 h-4" />
                            </button>
                        </div>
                    </div>
                )}
            </div>
        </div>
    );
}
