import React, { useEffect, useState } from 'react';
import { Loader2, AlertCircle, CheckCircle, XCircle, Clock, User } from 'lucide-react';

interface AuditLog {
    id: string;
    action: string;
    created_at: string;
    user?: {
        name: string;
        email: string;
        role: string;
    };
    details?: any;
}

interface JobHistoryTabProps {
    jobId: string;
}

export function JobHistoryTab({ jobId }: JobHistoryTabProps) {
    const [logs, setLogs] = useState<AuditLog[]>([]);
    const [isLoading, setIsLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);

    useEffect(() => {
        const fetchHistory = async () => {
            try {
                const response = await fetch(`/api/admin/jobs/moderation/${jobId}/history`);
                if (!response.ok) {
                    throw new Error('Failed to fetch history');
                }
                const data = await response.json();
                setLogs(data.logs || []);
            } catch (err: any) {
                console.error(err);
                setError(err.message || 'An error occurred fetching history');
            } finally {
                setIsLoading(false);
            }
        };

        fetchHistory();
    }, [jobId]);

    if (isLoading) {
        return (
            <div className="flex justify-center items-center h-64 text-gray-400">
                <Loader2 className="w-8 h-8 animate-spin" />
            </div>
        );
    }

    if (error) {
        return (
            <div className="flex items-center gap-2 p-4 text-red-500 bg-red-500/10 rounded-lg">
                <AlertCircle className="w-5 h-5" />
                <p>{error}</p>
            </div>
        );
    }

    if (logs.length === 0) {
        return (
            <div className="text-center p-12 bg-gray-50 dark:bg-[#1A1D20] rounded-xl border border-gray-100 dark:border-white/5">
                <Clock className="w-12 h-12 text-gray-300 dark:text-gray-600 mx-auto mb-4" />
                <h3 className="text-lg font-medium text-gray-900 dark:text-white mb-2">No Moderation History</h3>
                <p className="text-gray-500 text-sm">
                    This job has not been actioned by a moderator yet.
                </p>
            </div>
        );
    }

    const getActionIcon = (action: string) => {
        if (action.includes('approve')) return <CheckCircle className="w-5 h-5 text-green-500" />;
        if (action.includes('reject')) return <XCircle className="w-5 h-5 text-red-500" />;
        return <AlertCircle className="w-5 h-5 text-blue-500" />;
    };

    const getActionLabel = (action: string) => {
        if (action === 'job.approved') return 'Approved Job';
        if (action === 'job.rejected' || action === 'job.rejected_advanced') return 'Rejected Job';
        return action.replace('job.', '').replace('_', ' ');
    };

    return (
        <div className="space-y-6">
            <div>
                <h3 className="text-lg font-semibold text-gray-900 dark:text-white">Audit Log</h3>
                <p className="text-sm text-gray-500 dark:text-gray-400">Complete history of moderation actions taken on this job.</p>
            </div>

            <div className="relative border-l border-gray-200 dark:border-gray-800 ml-3 space-y-8">
                {logs.map((log) => (
                    <div key={log.id} className="relative pl-6">
                        <span className="absolute -left-3 top-1 bg-white dark:bg-[#1A1D20] p-1 rounded-full border border-gray-200 dark:border-gray-800">
                            {getActionIcon(log.action)}
                        </span>

                        <div className="bg-gray-50 dark:bg-[#1A1D20] border border-gray-100 dark:border-white/5 rounded-xl p-4 shadow-sm">
                            <div className="flex justify-between items-start mb-2">
                                <div>
                                    <h4 className="font-medium text-gray-900 dark:text-white capitalize">
                                        {getActionLabel(log.action)}
                                    </h4>
                                    <div className="flex items-center gap-2 mt-1 text-sm text-gray-500 dark:text-gray-400">
                                        <User className="w-4 h-4" />
                                        <span>{log.user?.name || log.user?.email || 'System Action'}</span>
                                        <span className="px-2 py-0.5 bg-gray-200 dark:bg-gray-800 rounded-full text-xs">
                                            {log.user?.role || 'System'}
                                        </span>
                                    </div>
                                </div>
                                <span className="text-xs text-gray-400 flex items-center gap-1">
                                    <Clock className="w-3 h-3" />
                                    {new Date(log.created_at).toLocaleString()}
                                </span>
                            </div>

                            {/* Detailed render based on action */}
                            {log.details && (
                                <div className="mt-4 pt-4 border-t border-gray-200 dark:border-gray-800 text-sm">
                                    {log.action.includes('reject') ? (
                                        <div className="space-y-2">
                                            <div className="grid grid-cols-2 gap-4">
                                                <div>
                                                    <span className="text-gray-500 block text-xs uppercase tracking-wider">Category</span>
                                                    <span className="text-gray-900 dark:text-white">{log.details.primaryCategory || 'General'}</span>
                                                </div>
                                                <div>
                                                    <span className="text-gray-500 block text-xs uppercase tracking-wider">Severity</span>
                                                    <span className="text-gray-900 dark:text-white capitalize">{log.details.severity || 'Medium'}</span>
                                                </div>
                                            </div>
                                            <div>
                                                <span className="text-gray-500 block text-xs uppercase tracking-wider mt-2">Reason</span>
                                                <span className="text-gray-900 dark:text-white font-medium">{log.details.primaryReason || 'N/A'}</span>
                                            </div>
                                            {log.details.detailedExplanation && (
                                                <div className="bg-white dark:bg-[#111315] p-3 rounded-lg border border-gray-100 dark:border-white/5 mt-2">
                                                    <p className="text-gray-600 dark:text-gray-300 italic">"{log.details.detailedExplanation}"</p>
                                                </div>
                                            )}
                                        </div>
                                    ) : (
                                        <div className="space-y-2">
                                            <div className="grid grid-cols-2 gap-4">
                                                <div>
                                                    <span className="text-gray-500 block text-xs uppercase tracking-wider">Previous Status</span>
                                                    <span className="text-gray-900 dark:text-white capitalize">{log.details.previous_status || 'Pending'}</span>
                                                </div>
                                                <div>
                                                    <span className="text-gray-500 block text-xs uppercase tracking-wider">New Status</span>
                                                    <span className="text-green-600 dark:text-green-400 font-medium capitalize">{log.details.new_status || 'Published'}</span>
                                                </div>
                                            </div>
                                            {log.details.adminNote && (
                                                <div className="mt-3">
                                                    <span className="text-gray-500 block text-xs uppercase tracking-wider">Admin Note</span>
                                                    <div className="bg-white dark:bg-[#111315] p-3 rounded-lg border border-gray-100 dark:border-white/5 mt-1">
                                                        <p className="text-gray-600 dark:text-gray-300">{log.details.adminNote}</p>
                                                    </div>
                                                </div>
                                            )}
                                        </div>
                                    )}
                                </div>
                            )}
                        </div>
                    </div>
                ))}
            </div>
        </div>
    );
}
