import React, { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { 
  X, 
  Loader2, 
  CheckCircle2, 
  XCircle, 
  Clock, 
  AlertCircle,
  Trash2,
  Pause,
  Play,
  List
} from 'lucide-react';
import { cn } from '@/utils';
import { TasksService } from '@/lib/api';
import { useCanvasStore } from '@/lib/store/canvasStore';

interface GenerationTask {
  id: string;
  type: 'image' | 'video' | 'audio' | 'music';
  status: 'pending' | 'running' | 'completed' | 'failed' | 'cancelled';
  progress: number;
  prompt?: string;
  createdAt: number;
  startedAt?: number;
  completedAt?: number;
  error?: string;
  result?: any;
}

interface GenerationQueuePanelProps {
  isOpen: boolean;
  onClose: () => void;
}

export function GenerationQueuePanel({ isOpen, onClose }: GenerationQueuePanelProps) {
  const [tasks, setTasks] = useState<GenerationTask[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [activeTab, setActiveTab] = useState<'all' | 'running' | 'completed' | 'failed'>('all');
  
  // Get generation history from canvas store
  const generationHistory = useCanvasStore((state) => state.generationHistory);

  useEffect(() => {
    if (isOpen) {
      fetchTasks();
      // Poll every 3 seconds
      const interval = setInterval(fetchTasks, 3000);
      return () => clearInterval(interval);
    }
  }, [isOpen]);

  const fetchTasks = async () => {
    try {
      const response = await TasksService.listTasks();
      if (response.data) {
        setTasks(response.data as GenerationTask[]);
      }
    } catch (error) {
      console.error('Failed to fetch tasks:', error);
    }
  };

  const cancelTask = async (taskId: string) => {
    try {
      await TasksService.cancelTask(taskId);
      fetchTasks();
    } catch (error) {
      console.error('Failed to cancel task:', error);
    }
  };

  const clearCompleted = () => {
    setTasks((prev) => prev.filter((t) => t.status === 'running' || t.status === 'pending'));
  };

  const filteredTasks = tasks.filter((task) => {
    if (activeTab === 'all') return true;
    return task.status === activeTab;
  });

  const stats = {
    total: tasks.length,
    pending: tasks.filter((t) => t.status === 'pending').length,
    running: tasks.filter((t) => t.status === 'running').length,
    completed: tasks.filter((t) => t.status === 'completed').length,
    failed: tasks.filter((t) => t.status === 'failed').length,
  };

  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'running':
        return <Loader2 className="w-4 h-4 text-blue-400 animate-spin" />;
      case 'completed':
        return <CheckCircle2 className="w-4 h-4 text-green-400" />;
      case 'failed':
        return <XCircle className="w-4 h-4 text-red-400" />;
      case 'cancelled':
        return <AlertCircle className="w-4 h-4 text-yellow-400" />;
      default:
        return <Clock className="w-4 h-4 text-muted-foreground" />;
    }
  };

  const getStatusText = (status: string) => {
    switch (status) {
      case 'running':
        return '生成中';
      case 'completed':
        return '已完成';
      case 'failed':
        return '失败';
      case 'cancelled':
        return '已取消';
      default:
        return '等待中';
    }
  };

  const getTypeIcon = (type: string) => {
    switch (type) {
      case 'image':
        return '🖼️';
      case 'video':
        return '🎬';
      case 'audio':
        return '🔊';
      case 'music':
        return '🎵';
      default:
        return '📄';
    }
  };

  return (
    <AnimatePresence>
      {isOpen && (
        <>
          {/* Backdrop */}
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 z-[9998] bg-black/40 backdrop-blur-sm"
            onClick={onClose}
          />

          {/* Panel */}
          <motion.div
            initial={{ opacity: 0, x: 300 }}
            animate={{ opacity: 1, x: 0 }}
            exit={{ opacity: 0, x: 300 }}
            transition={{ type: 'spring', damping: 25, stiffness: 200 }}
            className="fixed right-0 top-0 bottom-0 w-[400px] z-[9999] bg-black/80 backdrop-blur-xl border-l border-white/10 shadow-2xl flex flex-col"
          >
            {/* Header */}
            <div className="flex items-center justify-between p-4 border-b border-white/10">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 rounded-xl bg-gradient-to-br from-purple-500 to-pink-500 flex items-center justify-center">
                  <List className="w-5 h-5 text-white" />
                </div>
                <div>
                  <h2 className="text-lg font-semibold text-white">生成队列</h2>
                  <p className="text-xs text-muted-foreground">
                    {stats.running > 0 ? `${stats.running} 个任务运行中` : '队列空闲'}
                  </p>
                </div>
              </div>
              <button
                onClick={onClose}
                className="p-2 text-muted-foreground hover:text-white hover:bg-white/10 rounded-lg transition-colors"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            {/* Stats */}
            <div className="grid grid-cols-4 gap-2 p-4 border-b border-white/10">
              {[
                { label: '等待', value: stats.pending, color: 'text-yellow-400' },
                { label: '运行', value: stats.running, color: 'text-blue-400' },
                { label: '完成', value: stats.completed, color: 'text-green-400' },
                { label: '失败', value: stats.failed, color: 'text-red-400' },
              ].map((stat) => (
                <div key={stat.label} className="text-center p-2 bg-white/5 rounded-lg">
                  <p className={cn("text-xl font-bold", stat.color)}>{stat.value}</p>
                  <p className="text-[10px] text-muted-foreground uppercase">{stat.label}</p>
                </div>
              ))}
            </div>

            {/* Tabs */}
            <div className="flex items-center gap-1 p-2 border-b border-white/10">
              {(['all', 'running', 'completed', 'failed'] as const).map((tab) => (
                <button
                  key={tab}
                  onClick={() => setActiveTab(tab)}
                  className={cn(
                    "flex-1 px-3 py-2 text-xs font-medium rounded-lg transition-colors",
                    activeTab === tab
                      ? "bg-white/10 text-white"
                      : "text-muted-foreground hover:text-white hover:bg-white/5"
                  )}
                >
                  {tab === 'all' && '全部'}
                  {tab === 'running' && '运行中'}
                  {tab === 'completed' && '已完成'}
                  {tab === 'failed' && '失败'}
                </button>
              ))}
            </div>

            {/* Task List */}
            <div className="flex-1 overflow-y-auto p-4 space-y-3">
              {filteredTasks.length === 0 ? (
                <div className="flex flex-col items-center justify-center h-full text-muted-foreground">
                  <List className="w-12 h-12 mb-4 opacity-20" />
                  <p className="text-sm">暂无任务</p>
                  <p className="text-xs opacity-60">创建生成节点开始任务</p>
                </div>
              ) : (
                filteredTasks.map((task) => (
                  <motion.div
                    key={task.id}
                    layout
                    initial={{ opacity: 0, y: 20 }}
                    animate={{ opacity: 1, y: 0 }}
                    exit={{ opacity: 0, y: -20 }}
                    className={cn(
                      "p-3 rounded-xl border transition-all",
                      task.status === 'running'
                        ? "bg-blue-500/10 border-blue-500/30"
                        : task.status === 'completed'
                        ? "bg-green-500/10 border-green-500/30"
                        : task.status === 'failed'
                        ? "bg-red-500/10 border-red-500/30"
                        : "bg-white/5 border-white/10"
                    )}
                  >
                    <div className="flex items-start gap-3">
                      <div className="text-lg">{getTypeIcon(task.type)}</div>
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center gap-2 mb-1">
                          {getStatusIcon(task.status)}
                          <span className={cn(
                            "text-xs font-medium",
                            task.status === 'running' && "text-blue-400",
                            task.status === 'completed' && "text-green-400",
                            task.status === 'failed' && "text-red-400"
                          )}>
                            {getStatusText(task.status)}
                          </span>
                        </div>
                        <p className="text-sm text-white truncate">
                          {task.prompt || '未命名任务'}
                        </p>
                        <p className="text-[10px] text-muted-foreground">
                          {new Date(task.createdAt).toLocaleTimeString()}
                        </p>
                      </div>
                      {task.status === 'running' && (
                        <button
                          onClick={() => cancelTask(task.id)}
                          className="p-1.5 text-muted-foreground hover:text-red-400 hover:bg-red-500/20 rounded-lg transition-colors"
                          title="取消任务"
                        >
                          <Pause className="w-4 h-4" />
                        </button>
                      )}
                    </div>

                    {/* Progress bar for running tasks */}
                    {task.status === 'running' && (
                      <div className="mt-3">
                        <div className="h-1 bg-white/10 rounded-full overflow-hidden">
                          <motion.div
                            className="h-full bg-blue-400"
                            initial={{ width: 0 }}
                            animate={{ width: `${task.progress || 0}%` }}
                            transition={{ duration: 0.5 }}
                          />
                        </div>
                        <p className="text-[10px] text-muted-foreground mt-1">
                          {task.progress || 0}%
                        </p>
                      </div>
                    )}

                    {/* Error message for failed tasks */}
                    {task.status === 'failed' && task.error && (
                      <p className="mt-2 text-xs text-red-400 bg-red-500/10 p-2 rounded">
                        {task.error}
                      </p>
                    )}
                  </motion.div>
                ))
              )}
            </div>

            {/* Footer */}
            <div className="p-4 border-t border-white/10">
              <button
                onClick={clearCompleted}
                disabled={stats.completed === 0}
                className="w-full flex items-center justify-center gap-2 px-4 py-2 text-sm text-muted-foreground hover:text-white hover:bg-white/10 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
              >
                <Trash2 className="w-4 h-4" />
                清除已完成任务
              </button>
            </div>
          </motion.div>
        </>
      )}
    </AnimatePresence>
  );
}
