/**
 * SchedulerPanel - ZCLAW Scheduler UI
 *
 * Displays scheduled jobs, event triggers, workflows, and run history.
 *
 * Design based on ZCLAW Dashboard v0.4.0
 */

import { useState, useEffect, useCallback } from 'react';
import { useHandStore } from '../store/handStore';
import { useWorkflowStore, type Workflow } from '../store/workflowStore';
import { useAgentStore } from '../store/agentStore';
import { useConfigStore } from '../store/configStore';
import { WorkflowEditor } from './WorkflowEditor';
import { WorkflowHistory } from './WorkflowHistory';
import { TriggersPanel } from './TriggersPanel';
import {
  Clock,
  Zap,
  History,
  Plus,
  RefreshCw,
  Loader2,
  Calendar,
  X,
  AlertCircle,
  CheckCircle,
  GitBranch,
  Play,
} from 'lucide-react';

// === Tab Types ===

type TabType = 'scheduled' | 'triggers' | 'workflows' | 'history';

// === Schedule Type ===

type ScheduleType = 'cron' | 'interval' | 'once';
type TargetType = 'agent' | 'hand' | 'workflow';

// === Form State Interface ===

interface JobFormData {
  name: string;
  scheduleType: ScheduleType;
  cronExpression: string;
  intervalValue: number;
  intervalUnit: 'minutes' | 'hours' | 'days';
  runOnceDate: string;
  runOnceTime: string;
  targetType: TargetType;
  targetId: string;
  description: string;
  enabled: boolean;
}

const initialFormData: JobFormData = {
  name: '',
  scheduleType: 'cron',
  cronExpression: '',
  intervalValue: 30,
  intervalUnit: 'minutes',
  runOnceDate: '',
  runOnceTime: '',
  targetType: 'hand',
  targetId: '',
  description: '',
  enabled: true,
};

// === Tab Button Component ===

function TabButton({
  active,
  onClick,
  icon: Icon,
  label,
}: {
  active: boolean;
  onClick: () => void;
  icon: React.ComponentType<{ className?: string }>;
  label: string;
}) {
  return (
    <button
      onClick={onClick}
      className={`flex items-center gap-1.5 px-3 py-1.5 text-sm rounded-md transition-colors ${
        active
          ? 'bg-white dark:bg-gray-700 text-gray-900 dark:text-white shadow-sm'
          : 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white'
      }`}
    >
      <Icon className="w-3.5 h-3.5" />
      {label}
    </button>
  );
}

// === Empty State Component ===

function EmptyState({
  icon: Icon,
  title,
  description,
  actionLabel,
  onAction,
}: {
  icon: React.ComponentType<{ className?: string }>;
  title: string;
  description: string;
  actionLabel?: string;
  onAction?: () => void;
}) {
  return (
    <div className="text-center py-8">
      <div className="w-12 h-12 bg-gray-100 dark:bg-gray-800 rounded-full flex items-center justify-center mx-auto mb-3">
        <Icon className="w-6 h-6 text-gray-400" />
      </div>
      <p className="text-sm text-gray-500 dark:text-gray-400 mb-2">{title}</p>
      <p className="text-xs text-gray-400 dark:text-gray-500 mb-4 max-w-sm mx-auto">
        {description}
      </p>
      {actionLabel && onAction && (
        <button
          onClick={onAction}
          className="inline-flex items-center gap-1.5 px-3 py-1.5 text-sm bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
        >
          <Plus className="w-4 h-4" />
          {actionLabel}
        </button>
      )}
    </div>
  );
}

// === Create Job Modal Component ===

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

function CreateJobModal({ isOpen, onClose, onSuccess }: CreateJobModalProps) {
  // Store state - use domain stores
  const hands = useHandStore((s) => s.hands);
  const workflows = useWorkflowStore((s) => s.workflows);
  const clones = useAgentStore((s) => s.clones);
  const createScheduledTask = useConfigStore((s) => s.createScheduledTask);
  const loadHands = useHandStore((s) => s.loadHands);
  const loadWorkflows = useWorkflowStore((s) => s.loadWorkflows);
  const loadClones = useAgentStore((s) => s.loadClones);
  const [formData, setFormData] = useState<JobFormData>(initialFormData);
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [submitStatus, setSubmitStatus] = useState<'idle' | 'success' | 'error'>('idle');
  const [errorMessage, setErrorMessage] = useState('');

  // Load available targets on mount
  useEffect(() => {
    if (isOpen) {
      loadHands();
      loadWorkflows();
      loadClones();
    }
  }, [isOpen, loadHands, loadWorkflows, loadClones]);

  // Reset form when modal opens
  useEffect(() => {
    if (isOpen) {
      setFormData(initialFormData);
      setErrors({});
      setSubmitStatus('idle');
      setErrorMessage('');
    }
  }, [isOpen]);

  // Generate schedule string based on type
  const generateScheduleString = useCallback((): string => {
    switch (formData.scheduleType) {
      case 'cron':
        return formData.cronExpression;
      case 'interval': {
        const unitMap = { minutes: 'm', hours: 'h', days: 'd' };
        return `every ${formData.intervalValue}${unitMap[formData.intervalUnit]}`;
      }
      case 'once': {
        if (formData.runOnceDate && formData.runOnceTime) {
          return `once ${formData.runOnceDate}T${formData.runOnceTime}`;
        }
        return '';
      }
      default:
        return '';
    }
  }, [formData]);

  // Validate form
  const validateForm = useCallback((): boolean => {
    const newErrors: Record<string, string> = {};

    if (!formData.name.trim()) {
      newErrors.name = '任务名称不能为空';
    }

    switch (formData.scheduleType) {
      case 'cron':
        if (!formData.cronExpression.trim()) {
          newErrors.cronExpression = 'Cron 表达式不能为空';
        } else if (!isValidCron(formData.cronExpression)) {
          newErrors.cronExpression = 'Cron 表达式格式无效';
        }
        break;
      case 'interval':
        if (formData.intervalValue <= 0) {
          newErrors.intervalValue = '间隔时间必须大于 0';
        }
        break;
      case 'once':
        if (!formData.runOnceDate) {
          newErrors.runOnceDate = '请选择执行日期';
        }
        if (!formData.runOnceTime) {
          newErrors.runOnceTime = '请选择执行时间';
        }
        break;
    }

    if (!formData.targetId) {
      newErrors.targetId = '请选择要执行的目标';
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  }, [formData]);

  // Simple cron expression validator
  const isValidCron = (expression: string): boolean => {
    // Basic validation: 5 or 6 fields separated by spaces
    const parts = expression.trim().split(/\s+/);
    return parts.length >= 5 && parts.length <= 6;
  };

  // Handle form submission
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!validateForm()) {
      return;
    }

    setIsSubmitting(true);
    setSubmitStatus('idle');
    setErrorMessage('');

    try {
      const schedule = generateScheduleString();
      await createScheduledTask({
        name: formData.name.trim(),
        schedule,
        scheduleType: formData.scheduleType,
        target: {
          type: formData.targetType,
          id: formData.targetId,
        },
        description: formData.description.trim() || undefined,
        enabled: formData.enabled,
      });

      setSubmitStatus('success');
      setTimeout(() => {
        onSuccess();
        onClose();
      }, 1500);
    } catch (err) {
      setSubmitStatus('error');
      setErrorMessage(err instanceof Error ? err.message : '创建任务失败');
    } finally {
      setIsSubmitting(false);
    }
  };

  // Update form field
  const updateField = <K extends keyof JobFormData>(field: K, value: JobFormData[K]) => {
    setFormData(prev => ({ ...prev, [field]: value }));
    // Clear error when field is updated
    if (errors[field]) {
      setErrors(prev => {
        const newErrors = { ...prev };
        delete newErrors[field];
        return newErrors;
      });
    }
  };

  // Get available targets based on type
  const getAvailableTargets = (): Array<{ id: string; name?: string }> => {
    switch (formData.targetType) {
      case 'agent':
        return clones.map(c => ({ id: c.id, name: c.name }));
      case 'hand':
        return hands.map(h => ({ id: h.id, name: h.name }));
      case 'workflow':
        return workflows.map(w => ({ id: w.id, name: w.name }));
      default:
        return [];
    }
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center">
      {/* Backdrop */}
      <div
        className="absolute inset-0 bg-black/50 backdrop-blur-sm"
        onClick={onClose}
      />

      {/* Modal */}
      <div className="relative bg-white dark:bg-gray-800 rounded-xl shadow-2xl w-full max-w-lg mx-4 max-h-[90vh] overflow-hidden flex flex-col">
        {/* Header */}
        <div className="flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700 flex-shrink-0">
          <div className="flex items-center gap-3">
            <div className="w-8 h-8 bg-blue-100 dark:bg-blue-900/30 rounded-lg flex items-center justify-center">
              <Clock className="w-4 h-4 text-blue-600 dark:text-blue-400" />
            </div>
            <div>
              <h2 className="text-lg font-semibold text-gray-900 dark:text-white">
                新建定时任务
              </h2>
              <p className="text-xs text-gray-500 dark:text-gray-400">
                创建一个定时执行的任务
              </p>
            </div>
          </div>
          <button
            onClick={onClose}
            className="p-1 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Form */}
        <form onSubmit={handleSubmit} className="flex-1 overflow-y-auto p-4 space-y-4">
          {/* Task Name */}
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              任务名称 <span className="text-red-500">*</span>
            </label>
            <input
              type="text"
              value={formData.name}
              onChange={(e) => updateField('name', e.target.value)}
              placeholder="例如: 每日数据同步"
              className={`w-full px-3 py-2 text-sm border rounded-lg bg-white dark:bg-gray-900 text-gray-900 dark:text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500 ${
                errors.name ? 'border-red-500' : 'border-gray-300 dark:border-gray-600'
              }`}
            />
            {errors.name && (
              <p className="mt-1 text-xs text-red-500 flex items-center gap-1">
                <AlertCircle className="w-3 h-3" />
                {errors.name}
              </p>
            )}
          </div>

          {/* Schedule Type */}
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              调度类型 <span className="text-red-500">*</span>
            </label>
            <div className="flex gap-2">
              {[
                { value: 'cron', label: 'Cron 表达式' },
                { value: 'interval', label: '固定间隔' },
                { value: 'once', label: '执行一次' },
              ].map((option) => (
                <button
                  key={option.value}
                  type="button"
                  onClick={() => updateField('scheduleType', option.value as ScheduleType)}
                  className={`flex-1 px-3 py-2 text-sm rounded-lg border transition-colors ${
                    formData.scheduleType === option.value
                      ? 'bg-blue-600 text-white border-blue-600'
                      : 'bg-white dark:bg-gray-900 text-gray-700 dark:text-gray-300 border-gray-300 dark:border-gray-600 hover:border-blue-500'
                  }`}
                >
                  {option.label}
                </button>
              ))}
            </div>
          </div>

          {/* Cron Expression */}
          {formData.scheduleType === 'cron' && (
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                Cron 表达式 <span className="text-red-500">*</span>
              </label>
              <input
                type="text"
                value={formData.cronExpression}
                onChange={(e) => updateField('cronExpression', e.target.value)}
                placeholder="0 9 * * * (每天 9:00)"
                className={`w-full px-3 py-2 text-sm border rounded-lg bg-white dark:bg-gray-900 text-gray-900 dark:text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500 font-mono ${
                  errors.cronExpression ? 'border-red-500' : 'border-gray-300 dark:border-gray-600'
                }`}
              />
              {errors.cronExpression && (
                <p className="mt-1 text-xs text-red-500 flex items-center gap-1">
                  <AlertCircle className="w-3 h-3" />
                  {errors.cronExpression}
                </p>
              )}
              <p className="mt-1 text-xs text-gray-400">
                格式: 分 时 日 月 周 (例如: 0 9 * * * 表示每天 9:00)
              </p>
            </div>
          )}

          {/* Interval Settings */}
          {formData.scheduleType === 'interval' && (
            <div className="flex gap-2">
              <div className="flex-1">
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  间隔时间 <span className="text-red-500">*</span>
                </label>
                <input
                  type="number"
                  min="1"
                  value={formData.intervalValue}
                  onChange={(e) => updateField('intervalValue', parseInt(e.target.value) || 0)}
                  className={`w-full px-3 py-2 text-sm border rounded-lg bg-white dark:bg-gray-900 text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-blue-500 ${
                    errors.intervalValue ? 'border-red-500' : 'border-gray-300 dark:border-gray-600'
                  }`}
                />
                {errors.intervalValue && (
                  <p className="mt-1 text-xs text-red-500 flex items-center gap-1">
                    <AlertCircle className="w-3 h-3" />
                    {errors.intervalValue}
                  </p>
                )}
              </div>
              <div className="w-32">
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  单位
                </label>
                <select
                  value={formData.intervalUnit}
                  onChange={(e) => updateField('intervalUnit', e.target.value as 'minutes' | 'hours' | 'days')}
                  className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-900 text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-blue-500"
                >
                  <option value="minutes">分钟</option>
                  <option value="hours">小时</option>
                  <option value="days">天</option>
                </select>
              </div>
            </div>
          )}

          {/* Run Once Settings */}
          {formData.scheduleType === 'once' && (
            <div className="flex gap-2">
              <div className="flex-1">
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  执行日期 <span className="text-red-500">*</span>
                </label>
                <input
                  type="date"
                  value={formData.runOnceDate}
                  onChange={(e) => updateField('runOnceDate', e.target.value)}
                  className={`w-full px-3 py-2 text-sm border rounded-lg bg-white dark:bg-gray-900 text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-blue-500 ${
                    errors.runOnceDate ? 'border-red-500' : 'border-gray-300 dark:border-gray-600'
                  }`}
                />
                {errors.runOnceDate && (
                  <p className="mt-1 text-xs text-red-500 flex items-center gap-1">
                    <AlertCircle className="w-3 h-3" />
                    {errors.runOnceDate}
                  </p>
                )}
              </div>
              <div className="flex-1">
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  执行时间 <span className="text-red-500">*</span>
                </label>
                <input
                  type="time"
                  value={formData.runOnceTime}
                  onChange={(e) => updateField('runOnceTime', e.target.value)}
                  className={`w-full px-3 py-2 text-sm border rounded-lg bg-white dark:bg-gray-900 text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-blue-500 ${
                    errors.runOnceTime ? 'border-red-500' : 'border-gray-300 dark:border-gray-600'
                  }`}
                />
                {errors.runOnceTime && (
                  <p className="mt-1 text-xs text-red-500 flex items-center gap-1">
                    <AlertCircle className="w-3 h-3" />
                    {errors.runOnceTime}
                  </p>
                )}
              </div>
            </div>
          )}

          {/* Target Selection */}
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              执行目标类型
            </label>
            <div className="flex gap-2">
              {[
                { value: 'hand', label: 'Hand' },
                { value: 'workflow', label: 'Workflow' },
                { value: 'agent', label: 'Agent' },
              ].map((option) => (
                <button
                  key={option.value}
                  type="button"
                  onClick={() => {
                    updateField('targetType', option.value as TargetType);
                    updateField('targetId', ''); // Reset target when type changes
                  }}
                  className={`flex-1 px-3 py-2 text-sm rounded-lg border transition-colors ${
                    formData.targetType === option.value
                      ? 'bg-blue-600 text-white border-blue-600'
                      : 'bg-white dark:bg-gray-900 text-gray-700 dark:text-gray-300 border-gray-300 dark:border-gray-600 hover:border-blue-500'
                  }`}
                >
                  {option.label}
                </button>
              ))}
            </div>
          </div>

          {/* Target Selection Dropdown */}
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              选择目标 <span className="text-red-500">*</span>
            </label>
            <select
              value={formData.targetId}
              onChange={(e) => updateField('targetId', e.target.value)}
              className={`w-full px-3 py-2 text-sm border rounded-lg bg-white dark:bg-gray-900 text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-blue-500 ${
                errors.targetId ? 'border-red-500' : 'border-gray-300 dark:border-gray-600'
              }`}
            >
              <option value="">-- 请选择 --</option>
              {getAvailableTargets().map((target) => (
                <option key={target.id} value={target.id}>
                  {target.name || target.id}
                </option>
              ))}
            </select>
            {errors.targetId && (
              <p className="mt-1 text-xs text-red-500 flex items-center gap-1">
                <AlertCircle className="w-3 h-3" />
                {errors.targetId}
              </p>
            )}
            {getAvailableTargets().length === 0 && (
              <p className="mt-1 text-xs text-gray-400">
                当前没有可用的 {formData.targetType === 'hand' ? 'Hands' : formData.targetType === 'workflow' ? 'Workflows' : 'Agents'}
              </p>
            )}
          </div>

          {/* Description */}
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              任务描述
            </label>
            <textarea
              value={formData.description}
              onChange={(e) => updateField('description', e.target.value)}
              placeholder="可选的任务描述..."
              rows={2}
              className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-900 text-gray-900 dark:text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500 resize-none"
            />
          </div>

          {/* Enabled Toggle */}
          <div className="flex items-center gap-2">
            <input
              type="checkbox"
              id="enabled"
              checked={formData.enabled}
              onChange={(e) => updateField('enabled', e.target.checked)}
              className="w-4 h-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
            />
            <label htmlFor="enabled" className="text-sm text-gray-700 dark:text-gray-300">
              创建后立即启用
            </label>
          </div>

          {/* Status Messages */}
          {submitStatus === 'success' && (
            <div className="flex items-center gap-2 p-3 bg-green-50 dark:bg-green-900/20 rounded-lg text-green-700 dark:text-green-400">
              <CheckCircle className="w-5 h-5 flex-shrink-0" />
              <span className="text-sm">任务创建成功!</span>
            </div>
          )}
          {submitStatus === 'error' && (
            <div className="flex items-center gap-2 p-3 bg-red-50 dark:bg-red-900/20 rounded-lg text-red-700 dark:text-red-400">
              <AlertCircle className="w-5 h-5 flex-shrink-0" />
              <span className="text-sm">{errorMessage}</span>
            </div>
          )}
        </form>

        {/* Footer */}
        <div className="flex items-center justify-end gap-2 p-4 border-t border-gray-200 dark:border-gray-700 flex-shrink-0">
          <button
            type="button"
            onClick={onClose}
            disabled={isSubmitting}
            className="px-4 py-2 text-sm text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors disabled:opacity-50"
          >
            取消
          </button>
          <button
            type="submit"
            form="job-form"
            onClick={handleSubmit}
            disabled={isSubmitting || submitStatus === 'success'}
            className="px-4 py-2 text-sm text-white bg-blue-600 rounded-lg hover:bg-blue-700 transition-colors disabled:opacity-50 flex items-center gap-2"
          >
            {isSubmitting ? (
              <>
                <Loader2 className="w-4 h-4 animate-spin" />
                创建中...
              </>
            ) : (
              <>
                <Plus className="w-4 h-4" />
                创建任务
              </>
            )}
          </button>
        </div>
      </div>
    </div>
  );
}

// === Main SchedulerPanel Component ===

export function SchedulerPanel() {
  // Store state - use domain stores
  const scheduledTasks = useConfigStore((s) => s.scheduledTasks);
  const loadScheduledTasks = useConfigStore((s) => s.loadScheduledTasks);
  const workflows = useWorkflowStore((s) => s.workflows);
  const loadWorkflows = useWorkflowStore((s) => s.loadWorkflows);
  const createWorkflow = useWorkflowStore((s) => s.createWorkflow);
  const updateWorkflow = useWorkflowStore((s) => s.updateWorkflow);
  const executeWorkflow = useWorkflowStore((s) => s.triggerWorkflow);
  const handLoading = useHandStore((s) => s.isLoading);
  const workflowLoading = useWorkflowStore((s) => s.isLoading);
  const configLoading = useConfigStore((s) => s.isLoading);
  const isLoading = handLoading || workflowLoading || configLoading;
  const [activeTab, setActiveTab] = useState<TabType>('scheduled');
  const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
  const [isWorkflowEditorOpen, setIsWorkflowEditorOpen] = useState(false);
  const [editingWorkflow, setEditingWorkflow] = useState<Workflow | undefined>(undefined);
  const [selectedWorkflow, setSelectedWorkflow] = useState<Workflow | null>(null);
  const [isSavingWorkflow, setIsSavingWorkflow] = useState(false);

  useEffect(() => {
    loadScheduledTasks();
    loadWorkflows();
  }, [loadScheduledTasks, loadWorkflows]);

  const handleCreateJob = useCallback(() => {
    setIsCreateModalOpen(true);
  }, []);

  const handleCreateSuccess = useCallback(() => {
    loadScheduledTasks();
  }, [loadScheduledTasks]);

  // Workflow handlers
  const handleCreateWorkflow = useCallback(() => {
    setEditingWorkflow(undefined);
    setIsWorkflowEditorOpen(true);
  }, []);

  const handleEditWorkflow = useCallback((workflow: Workflow) => {
    setEditingWorkflow(workflow);
    setIsWorkflowEditorOpen(true);
  }, []);

  const handleViewWorkflowHistory = useCallback((workflow: Workflow) => {
    setSelectedWorkflow(workflow);
  }, []);

  const handleSaveWorkflow = useCallback(async (data: {
    name: string;
    description?: string;
    steps: Array<{
      handName: string;
      name?: string;
      params?: Record<string, unknown>;
      condition?: string;
    }>;
  }) => {
    setIsSavingWorkflow(true);
    try {
      if (editingWorkflow) {
        // Update existing workflow
        await updateWorkflow(editingWorkflow.id, data);
      } else {
        // Create new workflow
        await createWorkflow(data);
      }
      setIsWorkflowEditorOpen(false);
      setEditingWorkflow(undefined);
      await loadWorkflows();
    } catch (error) {
      console.error('Failed to save workflow:', error);
      throw error;
    } finally {
      setIsSavingWorkflow(false);
    }
  }, [editingWorkflow, createWorkflow, updateWorkflow, loadWorkflows]);

  const handleExecuteWorkflow = useCallback(async (workflowId: string) => {
    try {
      await executeWorkflow(workflowId);
      await loadWorkflows();
    } catch (error) {
      console.error('Failed to execute workflow:', error);
    }
  }, [executeWorkflow, loadWorkflows]);

  if (isLoading && scheduledTasks.length === 0) {
    return (
      <div className="p-4 text-center">
        <Loader2 className="w-6 h-6 animate-spin mx-auto text-gray-400 mb-2" />
        <p className="text-sm text-gray-500 dark:text-gray-400">
          加载调度器中...
        </p>
      </div>
    );
  }

  return (
    <>
      <div className="space-y-4">
        {/* Header */}
        <div className="flex items-start justify-between gap-4">
          <div>
            <h2 className="text-lg font-semibold text-gray-900 dark:text-white">
              调度器
            </h2>
            <p className="text-xs text-gray-500 dark:text-gray-400 mt-0.5">
              管理定时任务和事件触发器
            </p>
          </div>
          <button
            onClick={() => loadScheduledTasks()}
            disabled={isLoading}
            className="text-sm text-blue-600 dark:text-blue-400 hover:underline flex items-center gap-1 disabled:opacity-50"
          >
            {isLoading ? (
              <Loader2 className="w-3.5 h-3.5 animate-spin" />
            ) : (
              <RefreshCw className="w-3.5 h-3.5" />
            )}
            刷新
          </button>
        </div>

        {/* Tab Navigation */}
        <div className="flex items-center justify-between">
          <div className="flex items-center bg-gray-100 dark:bg-gray-800 rounded-lg p-1">
            <TabButton
              active={activeTab === 'scheduled'}
              onClick={() => setActiveTab('scheduled')}
              icon={Clock}
              label="定时任务"
            />
            <TabButton
              active={activeTab === 'triggers'}
              onClick={() => setActiveTab('triggers')}
              icon={Zap}
              label="事件触发器"
            />
            <TabButton
              active={activeTab === 'workflows'}
              onClick={() => setActiveTab('workflows')}
              icon={GitBranch}
              label="工作流"
            />
            <TabButton
              active={activeTab === 'history'}
              onClick={() => setActiveTab('history')}
              icon={History}
              label="运行历史"
            />
          </div>
          {activeTab === 'scheduled' && (
            <button
              onClick={handleCreateJob}
              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 transition-colors"
            >
              <Plus className="w-4 h-4" />
              新建任务
            </button>
          )}
          {activeTab === 'workflows' && (
            <button
              onClick={handleCreateWorkflow}
              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 transition-colors"
            >
              <Plus className="w-4 h-4" />
              新建工作流
            </button>
          )}
        </div>

        {/* Tab Content */}
        {activeTab === 'scheduled' && (
          <div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-4">
            {scheduledTasks.length === 0 ? (
              <EmptyState
                icon={Calendar}
                title="暂无定时任务"
                description="创建一个定时任务来定期运行代理。"
                actionLabel="创建定时任务"
                onAction={handleCreateJob}
              />
            ) : (
              <div className="space-y-2">
                {scheduledTasks.map((task) => (
                  <div
                    key={task.id}
                    className="flex items-center justify-between p-3 bg-gray-50 dark:bg-gray-900 rounded-lg"
                  >
                    <div className="flex items-center gap-3">
                      <div className="w-8 h-8 bg-blue-100 dark:bg-blue-900/30 rounded-lg flex items-center justify-center">
                        <Clock className="w-4 h-4 text-blue-600 dark:text-blue-400" />
                      </div>
                      <div>
                        <div className="font-medium text-gray-900 dark:text-white">
                          {task.name}
                        </div>
                        <div className="text-xs text-gray-500 dark:text-gray-400">
                          {task.schedule}
                        </div>
                      </div>
                    </div>
                    <div className="flex items-center gap-2">
                      <span
                        className={`px-2 py-0.5 rounded text-xs ${
                          task.status === 'active'
                            ? 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400'
                            : task.status === 'paused'
                            ? 'bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400'
                            : 'bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-400'
                        }`}
                      >
                        {task.status === 'active' ? '运行中' : task.status === 'paused' ? '已暂停' : task.status}
                      </span>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        )}

        {activeTab === 'triggers' && (
          <TriggersPanel />
        )}

        {/* Workflows Tab */}
        {activeTab === 'workflows' && (
          selectedWorkflow ? (
            <WorkflowHistory
              workflow={selectedWorkflow}
              onBack={() => setSelectedWorkflow(null)}
            />
          ) : (
            <div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-4">
              {workflows.length === 0 ? (
                <EmptyState
                  icon={GitBranch}
                  title="暂无工作流"
                  description="工作流可以将多个 Hand 组合成自动化流程，实现复杂的任务编排。"
                  actionLabel="创建工作流"
                  onAction={handleCreateWorkflow}
                />
              ) : (
                <div className="space-y-2">
                  {workflows.map((workflow) => (
                    <div
                      key={workflow.id}
                      className="flex items-center justify-between p-3 bg-gray-50 dark:bg-gray-900 rounded-lg"
                    >
                      <div className="flex items-center gap-3">
                        <div className="w-8 h-8 bg-purple-100 dark:bg-purple-900/30 rounded-lg flex items-center justify-center">
                          <GitBranch className="w-4 h-4 text-purple-600 dark:text-purple-400" />
                        </div>
                        <div>
                          <div className="font-medium text-gray-900 dark:text-white">
                            {workflow.name}
                          </div>
                          <div className="text-xs text-gray-500 dark:text-gray-400">
                            {workflow.description || '无描述'}
                          </div>
                        </div>
                      </div>
                      <div className="flex items-center gap-2">
                        {workflow.steps && (
                          <span className="text-xs text-gray-500 dark:text-gray-400">
                            {workflow.steps} 步骤
                          </span>
                        )}
                        <button
                          onClick={() => handleExecuteWorkflow(workflow.id)}
                          className="p-1.5 text-green-600 hover:bg-green-50 dark:hover:bg-green-900/20 rounded"
                          title="执行"
                        >
                          <Play className="w-4 h-4" />
                        </button>
                        <button
                          onClick={() => handleEditWorkflow(workflow)}
                          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"
                          title="编辑"
                        >
                          <GitBranch className="w-4 h-4" />
                        </button>
                        <button
                          onClick={() => handleViewWorkflowHistory(workflow)}
                          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"
                          title="历史"
                        >
                          <History className="w-4 h-4" />
                        </button>
                      </div>
                    </div>
                  ))}
                  <button
                    onClick={handleCreateWorkflow}
                    className="w-full flex items-center justify-center gap-2 p-3 border-2 border-dashed border-gray-200 dark:border-gray-700 rounded-lg text-gray-500 dark:text-gray-400 hover:border-blue-500 hover:text-blue-500 dark:hover:border-blue-400 dark:hover:text-blue-400 transition-colors"
                  >
                    <Plus className="w-4 h-4" />
                    创建新工作流
                  </button>
                </div>
              )}
            </div>
          )
        )}

        {activeTab === 'history' && (
          <div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-4">
            <EmptyState
              icon={History}
              title="暂无运行历史"
              description="当定时任务或事件触发器执行时，运行记录将显示在这里，包括状态和日志。"
            />
          </div>
        )}
      </div>

      {/* Create Job Modal */}
      <CreateJobModal
        isOpen={isCreateModalOpen}
        onClose={() => setIsCreateModalOpen(false)}
        onSuccess={handleCreateSuccess}
      />

      {/* Workflow Editor Modal */}
      <WorkflowEditor
        workflow={editingWorkflow}
        isOpen={isWorkflowEditorOpen}
        onClose={() => {
          setIsWorkflowEditorOpen(false);
          setEditingWorkflow(undefined);
        }}
        onSave={handleSaveWorkflow}
        isSaving={isSavingWorkflow}
      />
    </>
  );
}

export default SchedulerPanel;
