/**
 * HandTaskPanel - Hand 任务和结果面板
 *
 * 显示选中 Hand 的任务清单、执行历史和结果。
 * 使用真实 API 数据，移除了 Mock 数据。
 */

import { useState, useEffect, useCallback } from 'react';
import { useHandStore, type Hand, type HandRun } from '../store/handStore';
import {
  Zap,
  Loader2,
  Clock,
  CheckCircle,
  XCircle,
  AlertCircle,
  ChevronRight,
  Play,
  ArrowLeft,
  RefreshCw,
} from 'lucide-react';
import { useToast } from './ui/Toast';

interface HandTaskPanelProps {
  handId: string;
  onBack?: () => void;
}

// 任务状态配置
const RUN_STATUS_CONFIG: Record<string, { label: string; className: string; icon: React.ComponentType<{ className?: string }> }> = {
  pending: { label: '等待中', className: 'text-gray-500 bg-gray-100', icon: Clock },
  running: { label: '运行中', className: 'text-blue-600 bg-blue-100', icon: Loader2 },
  completed: { label: '已完成', className: 'text-green-600 bg-green-100', icon: CheckCircle },
  failed: { label: '失败', className: 'text-red-600 bg-red-100', icon: XCircle },
  cancelled: { label: '已取消', className: 'text-gray-500 bg-gray-100', icon: XCircle },
  needs_approval: { label: '待审批', className: 'text-yellow-600 bg-yellow-100', icon: AlertCircle },
  success: { label: '成功', className: 'text-green-600 bg-green-100', icon: CheckCircle },
  error: { label: '错误', className: 'text-red-600 bg-red-100', icon: XCircle },
};

export function HandTaskPanel({ handId, onBack }: HandTaskPanelProps) {
  const hands = useHandStore((s) => s.hands);
  const handRuns = useHandStore((s) => s.handRuns);
  const loadHands = useHandStore((s) => s.loadHands);
  const loadHandRuns = useHandStore((s) => s.loadHandRuns);
  const triggerHand = useHandStore((s) => s.triggerHand);
  const isLoading = useHandStore((s) => s.isLoading);
  const { toast } = useToast();
  const [selectedHand, setSelectedHand] = useState<Hand | null>(null);
  const [isActivating, setIsActivating] = useState(false);
  const [isRefreshing, setIsRefreshing] = useState(false);

  // Load hands on mount
  useEffect(() => {
    loadHands();
  }, [loadHands]);

  // Find selected hand
  useEffect(() => {
    const hand = hands.find(h => h.id === handId || h.name === handId);
    setSelectedHand(hand || null);
  }, [hands, handId]);

  // Load task history when hand is selected
  useEffect(() => {
    if (selectedHand) {
      loadHandRuns(selectedHand.id, { limit: 50 });
    }
  }, [selectedHand, loadHandRuns]);

  // Get runs for this hand from store
  const tasks: HandRun[] = selectedHand ? (handRuns[selectedHand.id] || []) : [];

  // Refresh task history
  const handleRefresh = useCallback(async () => {
    if (!selectedHand) return;
    setIsRefreshing(true);
    try {
      await loadHandRuns(selectedHand.id, { limit: 50 });
    } finally {
      setIsRefreshing(false);
    }
  }, [selectedHand, loadHandRuns]);

  // Trigger hand execution
  const handleActivate = useCallback(async () => {
    if (!selectedHand) return;

    // Check if hand is already running
    if (selectedHand.status === 'running') {
      toast(`Hand "${selectedHand.name}" 正在运行中，请等待完成`, 'warning');
      return;
    }

    setIsActivating(true);
    console.log(`[HandTaskPanel] Activating hand: ${selectedHand.id} (${selectedHand.name})`);

    try {
      const result = await triggerHand(selectedHand.id);
      console.log(`[HandTaskPanel] Activation result:`, result);

      if (result) {
        toast(`Hand "${selectedHand.name}" 已成功启动`, 'success');
        // Refresh hands list and task history
        await Promise.all([
          loadHands(),
          loadHandRuns(selectedHand.id, { limit: 50 }),
        ]);
      } else {
        // Check for specific error in store
        const storeError = useHandStore.getState().error;
        if (storeError?.includes('already active')) {
          toast(`Hand "${selectedHand.name}" 已在运行中`, 'warning');
        } else {
          toast(`Hand "${selectedHand.name}" 启动失败: ${storeError || '未知错误'}`, 'error');
        }
      }
    } catch (err) {
      const errorMsg = err instanceof Error ? err.message : String(err);
      console.error(`[HandTaskPanel] Activation error:`, errorMsg);

      if (errorMsg.includes('already active')) {
        toast(`Hand "${selectedHand.name}" 已在运行中`, 'warning');
      } else {
        toast(`Hand "${selectedHand.name}" 启动异常: ${errorMsg}`, 'error');
      }
    } finally {
      setIsActivating(false);
    }
  }, [selectedHand, triggerHand, loadHands, loadHandRuns, toast]);

  if (!selectedHand) {
    return (
      <div className="p-8 text-center">
        <Zap className="w-12 h-12 mx-auto text-gray-300 mb-3" />
        <p className="text-sm text-gray-400">请从左侧选择一个 Hand</p>
      </div>
    );
  }

  const runningTasks = tasks.filter(t => t.status === 'running');
  const completedTasks = tasks.filter(t => ['completed', 'success', 'failed', 'error', 'cancelled'].includes(t.status));
  const pendingTasks = tasks.filter(t => ['pending', 'needs_approval'].includes(t.status));

  return (
    <div className="h-full flex flex-col">
      {/* 头部 */}
      <div className="p-4 border-b border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 flex-shrink-0">
        <div className="flex items-center gap-3">
          {onBack && (
            <button
              onClick={onBack}
              className="p-1.5 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
            >
              <ArrowLeft className="w-4 h-4" />
            </button>
          )}
          <span className="text-2xl">{selectedHand.icon || '🤖'}</span>
          <div className="flex-1 min-w-0">
            <h2 className="text-lg font-semibold text-gray-900 dark:text-white truncate">
              {selectedHand.name}
            </h2>
            <p className="text-xs text-gray-500 dark:text-gray-400 truncate">{selectedHand.description}</p>
          </div>
          <button
            onClick={handleRefresh}
            disabled={isRefreshing}
            className="p-1.5 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors disabled:opacity-50"
            title="刷新"
          >
            <RefreshCw className={`w-4 h-4 ${isRefreshing ? 'animate-spin' : ''}`} />
          </button>
          <button
            onClick={handleActivate}
            disabled={selectedHand.status !== 'idle' || isActivating}
            className="flex items-center gap-1.5 px-3 py-1.5 text-sm bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
          >
            {isActivating ? (
              <>
                <Loader2 className="w-4 h-4 animate-spin" />
                启动中...
              </>
            ) : (
              <>
                <Play className="w-4 h-4" />
                执行任务
              </>
            )}
          </button>
        </div>
      </div>

      {/* 内容区域 */}
      <div className="flex-1 overflow-y-auto p-4 space-y-4">
        {/* 加载状态 */}
        {isLoading && tasks.length === 0 && (
          <div className="text-center py-8">
            <Loader2 className="w-8 h-8 mx-auto text-gray-400 animate-spin mb-3" />
            <p className="text-sm text-gray-500 dark:text-gray-400">加载任务历史中...</p>
          </div>
        )}

        {/* 运行中的任务 */}
        {runningTasks.length > 0 && (
          <div className="bg-blue-50 dark:bg-blue-900/20 rounded-lg p-4 border border-blue-200 dark:border-blue-800">
            <h3 className="text-sm font-semibold text-blue-700 dark:text-blue-400 mb-3 flex items-center gap-2">
              <Loader2 className="w-4 h-4 animate-spin" />
              运行中 ({runningTasks.length})
            </h3>
            <div className="space-y-2">
              {runningTasks.map(task => (
                <TaskCard key={task.runId} task={task} />
              ))}
            </div>
          </div>
        )}

        {/* 待处理任务 */}
        {pendingTasks.length > 0 && (
          <div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-4">
            <h3 className="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-3 flex items-center gap-2">
              <Clock className="w-4 h-4" />
              待处理 ({pendingTasks.length})
            </h3>
            <div className="space-y-2">
              {pendingTasks.map(task => (
                <TaskCard key={task.runId} task={task} />
              ))}
            </div>
          </div>
        )}

        {/* 已完成任务 */}
        {completedTasks.length > 0 && (
          <div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-4">
            <h3 className="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-3">
              历史记录 ({completedTasks.length})
            </h3>
            <div className="space-y-2">
              {completedTasks.map(task => (
                <TaskCard key={task.runId} task={task} expanded />
              ))}
            </div>
          </div>
        )}

        {/* 空状态 */}
        {!isLoading && tasks.length === 0 && (
          <div className="text-center py-12">
            <div className="w-16 h-16 bg-gray-100 dark:bg-gray-800 rounded-full flex items-center justify-center mx-auto mb-4">
              <Zap className="w-8 h-8 text-gray-400" />
            </div>
            <p className="text-sm text-gray-500 dark:text-gray-400 mb-1">暂无任务记录</p>
            <p className="text-xs text-gray-400 dark:text-gray-500">
              点击"执行任务"按钮开始运行
            </p>
          </div>
        )}
      </div>
    </div>
  );
}

// 任务卡片组件
function TaskCard({ task, expanded = false }: { task: HandRun; expanded?: boolean }) {
  const [isExpanded, setIsExpanded] = useState(expanded);
  const config = RUN_STATUS_CONFIG[task.status] || RUN_STATUS_CONFIG.pending;
  const StatusIcon = config.icon;

  // Format result for display
  const resultText = task.result
    ? (typeof task.result === 'string' ? task.result : JSON.stringify(task.result, null, 2))
    : undefined;

  return (
    <div className="bg-gray-50 dark:bg-gray-900 rounded-lg p-3 border border-gray-100 dark:border-gray-700">
      <div
        className="flex items-center justify-between cursor-pointer"
        onClick={() => setIsExpanded(!isExpanded)}
      >
        <div className="flex items-center gap-2 min-w-0">
          <StatusIcon className={`w-4 h-4 flex-shrink-0 ${task.status === 'running' ? 'animate-spin' : ''}`} />
          <span className="text-sm font-medium text-gray-800 dark:text-gray-200 truncate">
            运行 #{task.runId.slice(0, 8)}
          </span>
        </div>
        <div className="flex items-center gap-2 flex-shrink-0">
          <span className={`text-xs px-2 py-0.5 rounded ${config.className}`}>
            {config.label}
          </span>
          <ChevronRight className={`w-4 h-4 text-gray-400 transition-transform ${isExpanded ? 'rotate-90' : ''}`} />
        </div>
      </div>

      {/* 展开详情 */}
      {isExpanded && (
        <div className="mt-3 pt-3 border-t border-gray-200 dark:border-gray-700 space-y-2 text-xs text-gray-500 dark:text-gray-400">
          <div className="flex justify-between">
            <span>运行 ID</span>
            <span className="font-mono">{task.runId}</span>
          </div>
          <div className="flex justify-between">
            <span>开始时间</span>
            <span>{new Date(task.startedAt).toLocaleString()}</span>
          </div>
          {task.completedAt && (
            <div className="flex justify-between">
              <span>完成时间</span>
              <span>{new Date(task.completedAt).toLocaleString()}</span>
            </div>
          )}
          {resultText && (
            <div className="mt-2 p-2 bg-green-50 dark:bg-green-900/20 rounded border border-green-200 dark:border-green-800 text-green-700 dark:text-green-400 whitespace-pre-wrap max-h-40 overflow-auto">
              {resultText}
            </div>
          )}
          {task.error && (
            <div className="mt-2 p-2 bg-red-50 dark:bg-red-900/20 rounded border border-red-200 dark:border-red-800 text-red-700 dark:text-red-400">
              {task.error}
            </div>
          )}
        </div>
      )}
    </div>
  );
}

export default HandTaskPanel;
