import React, { useState } from 'react';
import { useExportQueue } from '../../context/ExportQueueContext';
import { Loader2, Download, Film, Image as ImageIcon, X, Zap } from 'lucide-react';

export const GlobalExportWidget: React.FC = () => {
  const { jobs, activeJobs, hasActiveJobs, downloadJob, cancelJob } = useExportQueue();
  const [isOpen, setIsOpen] = useState(false);

  if (jobs.length === 0) return null;

  return (
    <div className="fixed bottom-4 right-4 z-50 flex flex-col items-end gap-2" style={{ WebkitAppRegion: 'no-drag' } as React.CSSProperties}>
      {/* Popover list of jobs */}
      {isOpen && (
        <div className="w-80 bg-neutral-900 border border-neutral-700/50 rounded-xl shadow-2xl shadow-black/80 overflow-hidden flex flex-col animate-in slide-in-from-bottom-2 fade-in">
          <div className="flex items-center justify-between p-3 border-b border-neutral-800 bg-neutral-900">
            <h3 className="text-xs font-semibold text-white flex items-center gap-2">
              <Zap size={14} className="text-violet-400" />
              Cola de Renderizado
            </h3>
            <button 
              onClick={() => setIsOpen(false)}
              className="text-neutral-500 hover:text-white p-1 rounded-md hover:bg-neutral-800 transition-colors"
            >
              <X size={14} />
            </button>
          </div>

          <div className="max-h-[300px] overflow-y-auto custom-scrollbar bg-neutral-950 p-2 space-y-2">
            {jobs.map(job => {
              const isDone = job.status === 'done';
              const isError = job.status === 'error';
              const isWorking = job.status === 'rendering' || job.status === 'queued';
              const Icon = job.format === 'png' || job.format === 'jpeg' ? ImageIcon : Film;

              return (
                <div key={job.id} className="bg-neutral-900 border border-neutral-800 rounded-lg p-3 text-xs flex flex-col gap-2">
                  <div className="flex items-start justify-between">
                    <div className="flex items-center gap-2">
                      <Icon size={14} className={isDone ? 'text-green-400' : isError ? 'text-red-400' : 'text-violet-400'} />
                      <span className="font-medium text-neutral-200">
                        {job.format.toUpperCase()} ({job.width}x{job.height})
                      </span>
                    </div>
                    {isWorking && (
                      <button 
                        onClick={() => cancelJob(job.id)}
                        className="text-neutral-500 hover:text-red-400 p-1"
                        title="Cancelar render"
                      >
                        <X size={12} />
                      </button>
                    )}
                  </div>

                  {isWorking && (
                    <div className="flex flex-col gap-1">
                      <div className="flex items-center justify-between text-[10px]">
                        <span className="text-neutral-400">
                          {job.status === 'queued' ? 'En cola...' : 'Renderizando...'}
                        </span>
                        <span className="font-mono text-violet-400">{job.progress}%</span>
                      </div>
                      <div className="h-1.5 w-full bg-neutral-800 rounded-full overflow-hidden">
                        <div 
                          className="h-full bg-violet-500 transition-all duration-300" 
                          style={{ width: `${job.progress}%` }} 
                        />
                      </div>
                    </div>
                  )}

                  {isDone && (
                    <div className="flex items-center justify-between mt-1">
                      <span className="text-[10px] text-green-400 bg-green-500/10 px-2 py-0.5 rounded font-medium">Completado</span>
                      <button 
                        onClick={() => downloadJob(job)}
                        className="flex items-center gap-1 text-[10px] bg-violet-600 hover:bg-violet-500 text-white px-2 py-1 rounded transition-colors"
                      >
                        <Download size={12} /> Descargar
                      </button>
                    </div>
                  )}

                  {isError && (
                    <div className="mt-1">
                      <span className="text-[10px] text-red-400 bg-red-500/10 px-2 py-0.5 rounded font-medium">
                        {job.error || 'Error al renderizar'}
                      </span>
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* Floating Toggle Button */}
      <button
        onClick={() => setIsOpen(!isOpen)}
        className={`flex items-center gap-2 px-4 py-2.5 rounded-full shadow-lg shadow-black/50 transition-all border ${
          hasActiveJobs 
            ? 'bg-neutral-900 border-violet-500/50 text-white' 
            : 'bg-neutral-900 border-neutral-700/50 text-neutral-400 hover:text-white hover:border-neutral-600'
        }`}
      >
        {hasActiveJobs ? (
          <>
            <Loader2 size={16} className="animate-spin text-violet-400" />
            <span className="text-xs font-semibold">
              {activeJobs.length} renderizando...
            </span>
            <span className="text-[10px] font-mono text-violet-300 bg-violet-500/20 px-1.5 py-0.5 rounded ml-1">
              {activeJobs[0]?.progress || 0}%
            </span>
          </>
        ) : (
          <>
            <Zap size={16} />
            <span className="text-xs font-medium">Cola de Render ({jobs.length})</span>
          </>
        )}
      </button>
    </div>
  );
};
