import React, { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Progress } from '@/components/ui/progress';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { 
  Activity, 
  CheckCircle, 
  AlertCircle, 
  Clock,
  Eye,
  Download
} from 'lucide-react';
import { ComfyUIWebSocket } from '@/components/integrations/ComfyUIWebSocket';

export default function ComfyUITaskMonitor({ taskId, onComplete, onError }) {
  const [taskStatus, setTaskStatus] = useState('pending');
  const [progress, setProgress] = useState(0);
  const [currentNode, setCurrentNode] = useState('');
  const [results, setResults] = useState([]);
  const [ws, setWs] = useState(null);

  useEffect(() => {
    if (taskId) {
      initializeWebSocket();
    }

    return () => {
      if (ws) {
        ws.disconnect();
      }
    };
  }, [taskId]);

  const initializeWebSocket = async () => {
    try {
      const websocket = new ComfyUIWebSocket();
      
      websocket.setCallbacks({
        onStatus: (data) => {
          console.log('Status update:', data);
        },
        onProgress: (data) => {
          setProgress(data.value || 0);
          setCurrentNode(data.node || '');
        },
        onExecuting: (data) => {
          setTaskStatus('running');
          setCurrentNode(data.node || '正在处理...');
        },
        onExecuted: (data) => {
          if (data.node === taskId) {
            setTaskStatus('completed');
            setResults(data.output?.images || []);
            if (onComplete) {
              onComplete(data.output);
            }
          }
        },
        onError: (data) => {
          setTaskStatus('error');
          if (onError) {
            onError(data);
          }
        }
      });

      await websocket.connect();
      setWs(websocket);
      
    } catch (error) {
      console.error('Failed to connect to ComfyUI:', error);
      setTaskStatus('error');
    }
  };

  const getStatusColor = (status) => {
    const colors = {
      pending: 'bg-yellow-100 text-yellow-700',
      running: 'bg-blue-100 text-blue-700',
      completed: 'bg-green-100 text-green-700',
      error: 'bg-red-100 text-red-700'
    };
    return colors[status] || 'bg-gray-100 text-gray-700';
  };

  const getStatusIcon = (status) => {
    switch (status) {
      case 'pending':
        return <Clock className="w-4 h-4" />;
      case 'running':
        return <Activity className="w-4 h-4 animate-pulse" />;
      case 'completed':
        return <CheckCircle className="w-4 h-4" />;
      case 'error':
        return <AlertCircle className="w-4 h-4" />;
      default:
        return <Clock className="w-4 h-4" />;
    }
  };

  const getStatusText = (status) => {
    const texts = {
      pending: '等待中',
      running: '生成中',
      completed: '已完成',
      error: '生成失败'
    };
    return texts[status] || '未知状态';
  };

  return (
    <Card className="border-none shadow-lg bg-white/80 backdrop-blur-sm">
      <CardHeader>
        <CardTitle className="flex items-center justify-between">
          <span className="flex items-center gap-2">
            {getStatusIcon(taskStatus)}
            ComfyUI 任务监控
          </span>
          <Badge className={getStatusColor(taskStatus)}>
            {getStatusText(taskStatus)}
          </Badge>
        </CardTitle>
      </CardHeader>
      <CardContent className="space-y-4">
        {/* 进度条 */}
        {taskStatus === 'running' && (
          <div>
            <div className="flex justify-between text-sm mb-2">
              <span>生成进度</span>
              <span>{Math.round(progress)}%</span>
            </div>
            <Progress value={progress} className="h-2" />
            {currentNode && (
              <p className="text-xs text-slate-500 mt-1">
                当前节点: {currentNode}
              </p>
            )}
          </div>
        )}

        {/* 任务信息 */}
        <div className="text-sm text-slate-600">
          <p>任务ID: <span className="font-mono">{taskId}</span></p>
        </div>

        {/* 生成结果 */}
        {results.length > 0 && (
          <div>
            <h4 className="font-medium mb-2">生成结果</h4>
            <div className="grid grid-cols-2 gap-2">
              {results.map((result, index) => (
                <div key={index} className="relative group">
                  <img 
                    src={result.url} 
                    alt={`Result ${index + 1}`}
                    className="w-full aspect-square object-cover rounded-lg"
                  />
                  <div className="absolute inset-0 bg-black/50 opacity-0 group-hover:opacity-100 transition-opacity rounded-lg flex items-center justify-center gap-2">
                    <Button size="icon" variant="secondary" className="w-8 h-8">
                      <Eye className="w-4 h-4" />
                    </Button>
                    <Button size="icon" variant="secondary" className="w-8 h-8">
                      <Download className="w-4 h-4" />
                    </Button>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* 错误信息 */}
        {taskStatus === 'error' && (
          <div className="p-3 bg-red-50 border border-red-200 rounded-lg">
            <p className="text-red-700 text-sm">
              生成过程中出现错误，请检查ComfyUI服务状态或重试。
            </p>
          </div>
        )}
      </CardContent>
    </Card>
  );
}