import { useEffect, useState } from 'react';
import { formatDistanceToNow } from 'date-fns';
import { Activity, ShieldAlert, FileEdit, LogIn, ChevronLeft, ChevronRight } from 'lucide-react';

interface ActivityTabProps {
    userId: string;
}

export function ActivityTab({ userId }: ActivityTabProps) {
    const [activities, setActivities] = useState<any[]>([]);
    const [pagination, setPagination] = useState({ page: 1, totalPages: 1, limit: 15 });
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        async function fetchActivity() {
            setLoading(true);
            try {
                const res = await fetch(`/api/admin/users/${userId}/activity?page=${pagination.page}&limit=${pagination.limit}`);
                if (res.ok) {
                    const data = await res.json();
                    setActivities(data.activities);
                    setPagination(data.pagination);
                }
            } catch (error) {
                console.error("Failed to fetch activity", error);
            } finally {
                setLoading(false);
            }
        }
        fetchActivity();
    }, [userId, pagination.page, pagination.limit]);

    const getIcon = (action: string) => {
        if (action.includes('LOGIN') || action.includes('LOGOUT')) return <LogIn className="w-4 h-4 text-blue-500" />;
        if (action.includes('UPDATE') || action.includes('EDIT')) return <FileEdit className="w-4 h-4 text-amber-500" />;
        if (action.includes('DELETE') || action.includes('SUSPEND') || action.includes('SECURITY')) return <ShieldAlert className="w-4 h-4 text-red-500" />;
        return <Activity className="w-4 h-4 text-slate-500" />;
    };

    if (loading && activities.length === 0) {
        return <div className="p-12 text-center text-slate-500">Loading activity...</div>;
    }

    if (!loading && activities.length === 0) {
        return (
            <div className="bg-white rounded-xl shadow-sm border border-slate-200 p-12 text-center">
                <Activity className="w-8 h-8 text-slate-300 mx-auto mb-3" />
                <h3 className="text-sm font-medium text-slate-900">No activity found</h3>
                <p className="text-sm text-slate-500 mt-1">This user has not generated any system audit logs yet.</p>
            </div>
        );
    }

    return (
        <div className="bg-white rounded-xl shadow-sm border border-slate-200 overflow-hidden">
            <div className="p-6 border-b border-slate-200 flex justify-between items-center">
                <h3 className="text-lg font-bold text-slate-900">System Activity & Audit Logs</h3>
                <span className="text-sm text-slate-500">Page {pagination.page} of {pagination.totalPages || 1}</span>
            </div>

            <div className="p-0">
                <div className="flow-root">
                    <ul role="list" className="divide-y divide-slate-100">
                        {activities.map((activity, idx) => (
                            <li key={activity.id} className="p-6 hover:bg-slate-50 transition-colors">
                                <div className="flex space-x-4">
                                    <div className="flex-shrink-0 mt-1">
                                        <span className="h-8 w-8 rounded-full bg-slate-100 flex items-center justify-center ring-8 ring-white">
                                            {getIcon(activity.action)}
                                        </span>
                                    </div>
                                    <div className="flex-1 min-w-0">
                                        <div className="text-sm font-medium text-slate-900 flex justify-between">
                                            <span>
                                                <span className="font-bold text-slate-700">[{activity.action}]</span> — {activity.entity_type}
                                            </span>
                                            <span className="text-xs text-slate-400 whitespace-nowrap">
                                                {formatDistanceToNow(new Date(activity.created_at), { addSuffix: true })}
                                            </span>
                                        </div>
                                        <p className="mt-1 text-sm text-slate-500">
                                            IP: {activity.ip_address || 'Unknown'} • Source: {activity.user_agent ? activity.user_agent.split(' ')[0] : 'Unknown'}
                                        </p>
                                        {activity.details && Object.keys(activity.details).length > 0 && (
                                            <div className="mt-2 text-xs text-slate-600 bg-slate-50 p-3 rounded-lg border border-slate-200 overflow-x-auto font-mono">
                                                <pre>{JSON.stringify(activity.details, null, 2)}</pre>
                                            </div>
                                        )}
                                    </div>
                                </div>
                            </li>
                        ))}
                    </ul>
                </div>
            </div>

            {/* Pagination */}
            {pagination.totalPages > 1 && (
                <div className="bg-slate-50 border-t border-slate-200 px-6 py-3 flex items-center justify-between">
                    <button
                        onClick={() => setPagination(prev => ({ ...prev, page: Math.max(1, prev.page - 1) }))}
                        disabled={pagination.page === 1}
                        className="inline-flex items-center gap-1 text-sm font-medium text-slate-600 hover:text-slate-900 disabled:opacity-50"
                    >
                        <ChevronLeft className="w-4 h-4" /> Previous
                    </button>
                    <button
                        onClick={() => setPagination(prev => ({ ...prev, page: Math.min(pagination.totalPages, prev.page + 1) }))}
                        disabled={pagination.page === pagination.totalPages}
                        className="inline-flex items-center gap-1 text-sm font-medium text-slate-600 hover:text-slate-900 disabled:opacity-50"
                    >
                        Next <ChevronRight className="w-4 h-4" />
                    </button>
                </div>
            )}
        </div>
    );
}
