'use client';
import { useEffect, useState } from 'react';
import { getJobs, UploadJob } from '@/lib/api';
import { FileText, Clock, CheckCircle2, XCircle, RefreshCw } from 'lucide-react';

export default function UploadQueue({ 
  onSelectJob,
  selectedJobId
}: { 
  onSelectJob: (jobId: number | null) => void;
  selectedJobId: number | null;
}) {
  const [jobs, setJobs] = useState<UploadJob[]>([]);
  const [loading, setLoading] = useState(true);

  const fetchJobs = async () => {
    try {
      const data = await getJobs();
      setJobs(data);
    } catch (err) {
      console.error("Failed to fetch jobs:", err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchJobs();
    const interval = setInterval(fetchJobs, 5000);
    return () => clearInterval(interval);
  }, []);

  const getStatusIcon = (status: string) => {
    switch(status) {
      case 'COMPLETED': return <CheckCircle2 className="w-4 h-4 text-emerald-400" />;
      case 'FAILED': return <XCircle className="w-4 h-4 text-red-400" />;
      case 'PROCESSING': return <RefreshCw className="w-4 h-4 text-blue-400 animate-spin" />;
      default: return <Clock className="w-4 h-4 text-slate-400" />;
    }
  };

  return (
    <div className="bg-slate-800/50 rounded-xl border border-slate-700 p-4 h-full flex flex-col">
      <div className="flex items-center justify-between mb-4">
        <h2 className="text-lg font-semibold text-slate-200">Upload History</h2>
        {selectedJobId && (
          <button 
            onClick={() => onSelectJob(null)}
            className="text-xs text-indigo-400 hover:text-indigo-300"
          >
            Show All
          </button>
        )}
      </div>

      <div className="flex-1 overflow-y-auto pr-2 space-y-2 custom-scrollbar">
        {loading && jobs.length === 0 ? (
          <div className="text-center text-slate-500 py-4 text-sm">Loading...</div>
        ) : jobs.length === 0 ? (
          <div className="text-center text-slate-500 py-4 text-sm">No uploads yet.</div>
        ) : (
          jobs.map(job => (
            <button
              key={job.id}
              onClick={() => job.status === 'COMPLETED' ? onSelectJob(job.id) : null}
              className={`w-full text-left p-3 rounded-lg border transition-colors flex items-start gap-3
                ${selectedJobId === job.id 
                  ? 'bg-indigo-500/10 border-indigo-500/50 ring-1 ring-indigo-500/20' 
                  : 'bg-slate-800/80 border-slate-700/50 hover:bg-slate-700/50'
                }
                ${job.status !== 'COMPLETED' ? 'cursor-default opacity-80' : 'cursor-pointer hover:border-slate-600'}
              `}
            >
              <div className="mt-0.5">{getStatusIcon(job.status)}</div>
              <div className="flex-1 min-w-0">
                <div className="text-sm font-medium text-slate-200 truncate" title={job.filename}>
                  {job.filename}
                </div>
                <div className="text-xs text-slate-400 mt-1 flex items-center justify-between">
                  <span>{job.newspaper} • {job.date}</span>
                  <span className="text-[10px] uppercase tracking-wider font-semibold opacity-70">
                    {job.status}
                  </span>
                </div>
                {job.error_message && (
                  <div className="text-xs text-red-400 mt-1 truncate">
                    {job.error_message}
                  </div>
                )}
              </div>
            </button>
          ))
        )}
      </div>
    </div>
  );
}
