/**
 * AutomationPanel - Unified Automation Entry Point
 *
 * Combines Hands and Workflows into a single unified view,
 * with category filtering, batch operations, and scheduling.
 *
 * @module components/Automation/AutomationPanel
 */

import { useState, useEffect, useCallback, useMemo } from 'react';
import { useHandStore } from '../../store/handStore';
import { useWorkflowStore } from '../../store/workflowStore';
import {
  type AutomationItem,
  type CategoryType,
  type CategoryStats,
  adaptToAutomationItems,
  calculateCategoryStats,
  filterByCategory,
  searchAutomationItems,
} from '../../types/automation';
import { AutomationCard } from './AutomationCard';
import { AutomationFilters } from './AutomationFilters';
import { BatchActionBar } from './BatchActionBar';
import {
  Zap,
  RefreshCw,
  Plus,
  Calendar,
  Search,
  X,
} from 'lucide-react';
import { useToast } from '../ui/Toast';

// === View Mode ===

type ViewMode = 'grid' | 'list';

// === Component Props ===

interface AutomationPanelProps {
  initialCategory?: CategoryType;
  onSelect?: (item: AutomationItem) => void;
  showBatchActions?: boolean;
}

// === Main Component ===

export function AutomationPanel({
  initialCategory = 'all',
  onSelect,
  showBatchActions = true,
}: AutomationPanelProps) {
  // Store state - use domain stores
  const hands = useHandStore((s) => s.hands);
  const workflows = useWorkflowStore((s) => s.workflows);
  const handLoading = useHandStore((s) => s.isLoading);
  const workflowLoading = useWorkflowStore((s) => s.isLoading);
  const isLoading = handLoading || workflowLoading;
  const loadHands = useHandStore((s) => s.loadHands);
  const loadWorkflows = useWorkflowStore((s) => s.loadWorkflows);
  const triggerHand = useHandStore((s) => s.triggerHand);
  const triggerWorkflow = useWorkflowStore((s) => s.triggerWorkflow);

  // UI state
  const [selectedCategory, setSelectedCategory] = useState<CategoryType>(initialCategory);
  const [searchQuery, setSearchQuery] = useState('');
  const [viewMode, setViewMode] = useState<ViewMode>('grid');
  const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
  const [executingIds, setExecutingIds] = useState<Set<string>>(new Set());
  const [showWorkflowDialog, setShowWorkflowDialog] = useState(false);
  const [showSchedulerDialog, setShowSchedulerDialog] = useState(false);

  const { toast } = useToast();

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

  // Adapt hands and workflows to automation items
  const automationItems = useMemo<AutomationItem[]>(() => {
    return adaptToAutomationItems(hands, workflows);
  }, [hands, workflows]);

  // Calculate category stats
  const categoryStats = useMemo<CategoryStats>(() => {
    return calculateCategoryStats(automationItems);
  }, [automationItems]);

  // Filter and search items
  const filteredItems = useMemo<AutomationItem[]>(() => {
    let items = filterByCategory(automationItems, selectedCategory);
    if (searchQuery.trim()) {
      items = searchAutomationItems(items, searchQuery);
    }
    return items;
  }, [automationItems, selectedCategory, searchQuery]);

  // Selection handlers
  const handleSelect = useCallback((id: string, selected: boolean) => {
    setSelectedIds(prev => {
      const next = new Set(prev);
      if (selected) {
        next.add(id);
      } else {
        next.delete(id);
      }
      return next;
    });
  }, []);

  const handleSelectAll = useCallback(() => {
    setSelectedIds(new Set(filteredItems.map(item => item.id)));
  }, [filteredItems]);

  const handleDeselectAll = useCallback(() => {
    setSelectedIds(new Set());
  }, []);

  // Workflow dialog handlers
  const handleCreateWorkflow = useCallback(() => {
    setShowWorkflowDialog(true);
  }, []);

  const handleSchedulerManage = useCallback(() => {
    setShowSchedulerDialog(true);
  }, []);

  // Execute handler
  const handleExecute = useCallback(async (item: AutomationItem, params?: Record<string, unknown>) => {
    setExecutingIds(prev => new Set(prev).add(item.id));

    try {
      if (item.type === 'hand') {
        await triggerHand(item.id, params);
      } else {
        await triggerWorkflow(item.id, params);
      }
      toast(`${item.name} 执行成功`, 'success');
    } catch (err) {
      const errorMsg = err instanceof Error ? err.message : String(err);
      toast(`${item.name} 执行失败: ${errorMsg}`, 'error');
    } finally {
      setExecutingIds(prev => {
        const next = new Set(prev);
        next.delete(item.id);
        return next;
      });
    }
  }, [triggerHand, triggerWorkflow, toast]);

  // Batch execute
  const handleBatchExecute = useCallback(async () => {
    const itemsToExecute = filteredItems.filter(item => selectedIds.has(item.id));
    let successCount = 0;
    let failCount = 0;

    for (const item of itemsToExecute) {
      try {
        if (item.type === 'hand') {
          await triggerHand(item.id);
        } else {
          await triggerWorkflow(item.id);
        }
        successCount++;
      } catch {
        failCount++;
      }
    }

    if (successCount > 0) {
      toast(`成功执行 ${successCount} 个项目`, 'success');
    }
    if (failCount > 0) {
      toast(`${failCount} 个项目执行失败`, 'error');
    }

    setSelectedIds(new Set());
  }, [filteredItems, selectedIds, triggerHand, triggerWorkflow, toast]);

  // Refresh handler
  const handleRefresh = useCallback(async () => {
    await Promise.all([loadHands(), loadWorkflows()]);
    toast('数据已刷新', 'success');
  }, [loadHands, loadWorkflows, toast]);

  return (
    <div className="flex flex-col h-full">
      {/* Header */}
      <div className="flex items-center justify-between px-4 py-3 border-b border-gray-200 dark:border-gray-700">
        <div className="flex items-center gap-2">
          <Zap className="w-5 h-5 text-orange-500" />
          <h2 className="text-lg font-semibold text-gray-900 dark:text-white">
            自动化
          </h2>
          <span className="text-sm text-gray-500 dark:text-gray-400">
            ({automationItems.length})
          </span>
        </div>
        <div className="flex items-center gap-2">
          <button
            onClick={handleRefresh}
            disabled={isLoading}
            className="p-2 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300 disabled:opacity-50"
            title="刷新"
          >
            <RefreshCw className={`w-4 h-4 ${isLoading ? 'animate-spin' : ''}`} />
          </button>
          <button
            onClick={handleCreateWorkflow}
            className="p-2 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300"
            title="新建工作流"
          >
            <Plus className="w-4 h-4" />
          </button>
          <button
            onClick={handleSchedulerManage}
            className="p-2 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300"
            title="调度管理"
          >
            <Calendar className="w-4 h-4" />
          </button>
        </div>
      </div>

      {/* Filters */}
      <AutomationFilters
        selectedCategory={selectedCategory}
        onCategoryChange={setSelectedCategory}
        searchQuery={searchQuery}
        onSearchChange={setSearchQuery}
        viewMode={viewMode}
        onViewModeChange={setViewMode}
        categoryStats={categoryStats}
      />

      {/* Content */}
      <div className="flex-1 overflow-y-auto p-4">
        {isLoading && automationItems.length === 0 ? (
          <div className="flex items-center justify-center h-32">
            <RefreshCw className="w-6 h-6 animate-spin text-gray-400" />
          </div>
        ) : filteredItems.length === 0 ? (
          <div className="flex flex-col items-center justify-center h-32 text-center">
            <Search className="w-8 h-8 text-gray-400 mb-2" />
            <p className="text-sm text-gray-500 dark:text-gray-400">
              {searchQuery ? '没有找到匹配的项目' : '暂无自动化项目'}
            </p>
          </div>
        ) : (
          <div className={
            viewMode === 'grid'
              ? 'grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4'
              : 'flex flex-col gap-2'
          }>
            {filteredItems.map(item => (
              <AutomationCard
                key={item.id}
                item={item}
                viewMode={viewMode}
                isSelected={selectedIds.has(item.id)}
                isExecuting={executingIds.has(item.id)}
                onSelect={(selected) => handleSelect(item.id, selected)}
                onExecute={(params) => handleExecute(item, params)}
                onClick={() => onSelect?.(item)}
              />
            ))}
          </div>
        )}
      </div>

      {/* Batch Actions */}
      {showBatchActions && selectedIds.size > 0 && (
        <BatchActionBar
          selectedCount={selectedIds.size}
          totalCount={filteredItems.length}
          onSelectAll={handleSelectAll}
          onDeselectAll={handleDeselectAll}
          onBatchExecute={handleBatchExecute}
          onBatchSchedule={() => {
            toast('批量调度功能开发中', 'info');
          }}
        />
      )}

      {/* Create Workflow Dialog */}
      {showWorkflowDialog && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl w-full max-w-md mx-4">
            <div className="flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700">
              <h3 className="text-lg font-semibold text-gray-900 dark:text-white">新建工作流</h3>
              <button
                onClick={() => setShowWorkflowDialog(false)}
                className="p-1 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
              >
                <X className="w-5 h-5" />
              </button>
            </div>
            <div className="p-4">
              <div className="space-y-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    工作流名称
                  </label>
                  <input
                    type="text"
                    placeholder="输入工作流名称..."
                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-gray-400"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    描述
                  </label>
                  <textarea
                    placeholder="描述这个工作流的用途..."
                    rows={3}
                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-gray-400 resize-none"
                  />
                </div>
              </div>
            </div>
            <div className="flex justify-end gap-2 p-4 border-t border-gray-200 dark:border-gray-700">
              <button
                onClick={() => setShowWorkflowDialog(false)}
                className="px-4 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg"
              >
                取消
              </button>
              <button
                onClick={() => {
                  toast('工作流创建功能开发中', 'info');
                  setShowWorkflowDialog(false);
                }}
                className="px-4 py-2 text-sm bg-gray-700 dark:bg-gray-600 text-white rounded-lg hover:bg-gray-800 dark:hover:bg-gray-500"
              >
                创建
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Scheduler Dialog */}
      {showSchedulerDialog && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl w-full max-w-lg mx-4">
            <div className="flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700">
              <h3 className="text-lg font-semibold text-gray-900 dark:text-white">调度管理</h3>
              <button
                onClick={() => setShowSchedulerDialog(false)}
                className="p-1 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
              >
                <X className="w-5 h-5" />
              </button>
            </div>
            <div className="p-4">
              <div className="text-center py-8 text-gray-500 dark:text-gray-400">
                <Calendar className="w-12 h-12 mx-auto mb-3 opacity-50" />
                <p>调度管理功能开发中</p>
                <p className="text-sm mt-1">将支持定时执行、Cron 表达式配置等</p>
              </div>
            </div>
            <div className="flex justify-end p-4 border-t border-gray-200 dark:border-gray-700">
              <button
                onClick={() => setShowSchedulerDialog(false)}
                className="px-4 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg"
              >
                关闭
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

export default AutomationPanel;
