"use client";

import { useEffect, useState } from 'react';
import api from '../../../lib/api'; // Pfad prüfen: admin/audit-logs -> ../../../lib/api
import { UserInfo } from '../../../types';
import { useRouter } from 'next/navigation';
import {
    ClockIcon,
    UserIcon,
    ShieldExclamationIcon,
    DocumentTextIcon,
    ComputerDesktopIcon,
    ArrowPathIcon
} from '@heroicons/react/24/outline';

interface AuditLog {
    id: number;
    user_id: number | null;
    username: string;
    event_type: string;
    event_description: string;
    ip_address: string;
    resource_type: string;
    resource_id: string;
    timestamp: string;
}

const PAGE_SIZE = 100;

export default function AuditLogsPage() {
    const [logs, setLogs] = useState<AuditLog[]>([]);
    const [loading, setLoading] = useState(true);
    const [loadingMore, setLoadingMore] = useState(false);
    const [hasMore, setHasMore] = useState(true);
    const router = useRouter();

    useEffect(() => {
        fetchLogs(0, true);
    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    const fetchLogs = async (skip = 0, replace = false) => {
        try {
            if (replace) setLoading(true);
            else setLoadingMore(true);
            const res = await api.get('/audit/logs', { params: { skip, limit: PAGE_SIZE } });
            const incoming: AuditLog[] = Array.isArray(res.data) ? res.data : [];
            setHasMore(incoming.length === PAGE_SIZE);
            if (replace) {
                setLogs(incoming);
            } else {
                setLogs(prev => [...prev, ...incoming]);
            }
        } catch (error: any) {
            console.error("Failed to fetch logs", error);
            if (error.response?.status === 403) {
                router.push('/dashboard');
            }
        } finally {
            setLoading(false);
            setLoadingMore(false);
        }
    };

    const getEventIcon = (type: string) => {
        if (type.includes('login') || type.includes('logout')) return <UserIcon className="h-4 w-4 text-blue-500" />;
        if (type.includes('security') || type.includes('alert')) return <ShieldExclamationIcon className="h-4 w-4 text-red-500" />;
        if (type.includes('scan')) return <ArrowPathIcon className="h-4 w-4 text-green-500" />;
        if (type.includes('asset')) return <ComputerDesktopIcon className="h-4 w-4 text-purple-500" />;
        return <DocumentTextIcon className="h-4 w-4 text-gray-500" />;
    };

    const formatDate = (dateStr: string) => {
        return new Date(dateStr).toLocaleString();
    };

    if (loading) {
        return <div className="p-8 text-center text-gray-500 font-mono">Loading Audit Logs...</div>;
    }

    return (
        <div className="space-y-6">
            <div className="flex justify-between items-center">
                <h1 className="text-2xl font-bold text-gray-900 tracking-tight font-mono">
                    Audit Logs
                    <span className="ml-2 text-sm font-normal text-gray-500 bg-gray-100 px-2 py-0.5 rounded-full">
                        {logs.length} events
                    </span>
                </h1>
                <button
                    onClick={() => fetchLogs(0, true)}
                    className="p-2 text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded-lg transition-colors"
                    title="Refresh Logs"
                >
                    <ArrowPathIcon className="h-5 w-5" />
                </button>
            </div>

            <div className="bg-white border border-gray-200 shadow-sm rounded-lg overflow-hidden">
                <div className="overflow-x-auto">
                    <table className="min-w-full divide-y divide-gray-200">
                        <thead className="bg-gray-50">
                            <tr>
                                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider font-mono">Time</th>
                                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider font-mono">User</th>
                                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider font-mono">Event</th>
                                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider font-mono">Description</th>
                                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider font-mono">Resource</th>
                                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider font-mono">IP</th>
                            </tr>
                        </thead>
                        <tbody className="bg-white divide-y divide-gray-200 font-mono text-sm">
                            {logs.map((log) => (
                                <tr key={log.id} className="hover:bg-gray-50 transition-colors">
                                    <td className="px-6 py-4 whitespace-nowrap text-gray-500">
                                        <div className="flex items-center gap-2">
                                            <ClockIcon className="h-3 w-3" />
                                            {formatDate(log.timestamp)}
                                        </div>
                                    </td>
                                    <td className="px-6 py-4 whitespace-nowrap">
                                        <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${log.username === 'System/Deleted' ? 'bg-gray-100 text-gray-600' : 'bg-blue-50 text-blue-700'}`}>
                                            {log.username}
                                        </span>
                                    </td>
                                    <td className="px-6 py-4 whitespace-nowrap">
                                        <div className="flex items-center gap-2">
                                            {getEventIcon(log.event_type)}
                                            <span className="capitalize">{log.event_type.replace(/_/g, ' ')}</span>
                                        </div>
                                    </td>
                                    <td className="px-6 py-4 text-gray-900 max-w-xs truncate" title={log.event_description}>
                                        {log.event_description}
                                    </td>
                                    <td className="px-6 py-4 whitespace-nowrap text-gray-500">
                                        {log.resource_type && (
                                            <span className="px-2 py-0.5 bg-gray-100 rounded text-xs">
                                                {log.resource_type} {log.resource_id ? `#${log.resource_id}` : ''}
                                            </span>
                                        )}
                                    </td>
                                    <td className="px-6 py-4 whitespace-nowrap text-gray-500 text-xs">
                                        {log.ip_address || '-'}
                                    </td>
                                </tr>
                            ))}
                            {logs.length === 0 && (
                                <tr>
                                    <td colSpan={6} className="px-6 py-12 text-center text-gray-500">
                                        No audit logs found.
                                    </td>
                                </tr>
                            )}
                        </tbody>
                    </table>
                </div>
                {hasMore && (
                    <div className="border-t border-gray-200 p-3 text-center bg-gray-50">
                        <button
                            disabled={loadingMore}
                            onClick={() => fetchLogs(logs.length, false)}
                            className="text-sm font-mono px-4 py-1.5 rounded border border-gray-300 hover:bg-white disabled:opacity-60"
                        >
                            {loadingMore ? 'Loading…' : `Load next ${PAGE_SIZE}`}
                        </button>
                    </div>
                )}
            </div>
        </div>
    );
}
