import React, { useState, useEffect } from 'react';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import { Input } from '../ui/input';
import { Search, Filter, History, User, Activity, Globe, Loader2 } from 'lucide-react';
import { adminService } from '../../services/adminService';
import { format } from 'date-fns';

export const AdminAuditLogsView: React.FC = () => {
    const [logs, setLogs] = useState<any[]>([]);
    const [loading, setLoading] = useState(true);
    const [page, setPage] = useState(1);
    const [total, setTotal] = useState(0);

    const fetchLogs = async () => {
        setLoading(true);
        try {
            const data = await adminService.getAuditLogs({ page, limit: 20 });
            setLogs(data.logs || []);
            setTotal(data.pagination?.total_items || 0);
        } catch (e) {
            console.error('Failed to fetch audit logs', e);
        } finally {
            setLoading(false);
        }
    };

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

    return (
        <div className="space-y-6 animate-fadeIn h-full flex flex-col">
            <div className="flex justify-between items-center">
                <div>
                    <h2 className="text-2xl font-display font-bold text-white mb-1">AUDIT PROTOCOL</h2>
                    <p className="text-kodo-content-dim font-mono text-xs uppercase tracking-widest">Global Immutable Ledger</p>
                </div>
                <div className="flex gap-2">
                    <Button variant="ghost" size="sm" onClick={() => fetchLogs()} disabled={loading}>
                        <History className={`w-4 h-4 mr-2 ${loading ? 'animate-spin' : ''}`} /> Refresh
                    </Button>
                </div>
            </div>

            <div className="flex flex-col md:flex-row gap-4">
                <div className="relative flex-1">
                    <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-kodo-content-dim" />
                    <Input placeholder="Search action, user, or IP..." className="pl-10 h-10" />
                </div>
                <Button variant="outline" className="h-10 border-white/10 hover:border-primary/50">
                    <Filter className="w-4 h-4 mr-2" /> All Resources
                </Button>
            </div>

            <Card variant="glass" className="flex-1 overflow-hidden border-white/5 bg-black/40 flex flex-col p-0">
                <div className="overflow-x-auto">
                    <table className="w-full text-left border-collapse">
                        <thead>
                            <tr className="border-b border-white/5 bg-white/5 text-[10px] font-mono text-kodo-content-dim uppercase tracking-wider">
                                <th className="p-4">Timestamp</th>
                                <th className="p-4">User</th>
                                <th className="p-4">Action</th>
                                <th className="p-4">Resource</th>
                                <th className="p-4">Context</th>
                                <th className="p-4 text-right">Origin</th>
                            </tr>
                        </thead>
                        <tbody className="divide-y divide-white/5 text-sm">
                            {loading ? (
                                <tr>
                                    <td colSpan={6} className="p-12 text-center">
                                        <Loader2 className="w-8 h-8 text-primary animate-spin mx-auto" />
                                    </td>
                                </tr>
                            ) : logs.length === 0 ? (
                                <tr>
                                    <td colSpan={6} className="p-12 text-center text-kodo-content-dim font-mono uppercase text-xs">
                                        No temporal data packets recovered.
                                    </td>
                                </tr>
                            ) : (
                                logs.map((log) => (
                                    <tr key={log.id} className="hover:bg-white/5 transition-colors group border-white/5">
                                        <td className="p-4 font-mono text-[10px] text-kodo-content-dim">
                                            {format(new Date(log.timestamp), 'MMM dd, HH:mm:ss')}
                                        </td>
                                        <td className="p-4">
                                            <div className="flex items-center gap-2">
                                                <User className="w-3 h-3 text-primary/70" />
                                                <span className="font-bold text-white text-xs">{log.user?.username || 'System'}</span>
                                            </div>
                                        </td>
                                        <td className="p-4">
                                            <span className="px-2 py-0.5 bg-primary/10 text-primary border border-primary/20 rounded text-[10px] uppercase font-bold">
                                                {log.action}
                                            </span>
                                        </td>
                                        <td className="p-4 font-mono text-xs text-white/80">
                                            {log.resource} <span className="text-kodo-content-dim opacity-50">#{log.resource_id?.slice(0, 8)}</span>
                                        </td>
                                        <td className="p-4 text-[10px] text-kodo-content-dim max-w-[200px] truncate">
                                            {JSON.stringify(log.context)}
                                        </td>
                                        <td className="p-4 text-right">
                                            <div className="flex flex-col items-end">
                                                <span className="font-mono text-[10px] text-white/80 flex items-center gap-1">
                                                    <Globe className="w-2 h-2" /> {log.ip_address}
                                                </span>
                                                <span className="text-[9px] text-kodo-content-dim truncate max-w-[120px]" title={log.user_agent}>
                                                    {log.user_agent}
                                                </span>
                                            </div>
                                        </td>
                                    </tr>
                                ))
                            )}
                        </tbody>
                    </table>
                </div>

                {/* Pagination placeholder */}
                <div className="p-4 border-t border-white/5 bg-white/2 flex justify-between items-center mt-auto">
                    <span className="text-[10px] text-kodo-content-dim font-mono uppercase">
                        Packet: {logs.length} / Total: {total}
                    </span>
                    <div className="flex gap-2">
                        <Button variant="ghost" size="sm" onClick={() => setPage(p => Math.max(1, p - 1))} disabled={page === 1 || loading}>Previous</Button>
                        <Button variant="ghost" size="sm" onClick={() => setPage(p => p + 1)} disabled={logs.length < 20 || loading}>Next</Button>
                    </div>
                </div>
            </Card>
        </div>
    );
};
