/**
 * 工作流列表组件
 * 
 * 显示所有可用的AI工作流，支持筛选、搜索和管理
 * 遵循Tauri开发规范的组件设计原则
 */

import React, { useState, useEffect } from 'react';
import { Play, Settings, Eye, Edit, Trash2, Plus, Search, Filter } from 'lucide-react';
import { invoke } from '@tauri-apps/api/core';
import type { WorkflowTemplate } from '../../types/workflow';

interface WorkflowListProps {
  /** 选择工作流回调 */
  onSelectWorkflow?: (workflow: WorkflowTemplate) => void;
  /** 执行工作流回调 */
  onExecuteWorkflow?: (workflow: WorkflowTemplate) => void;
  /** 编辑工作流回调 */
  onEditWorkflow?: (workflow: WorkflowTemplate) => void;
  /** 是否显示管理按钮 */
  showManagement?: boolean;
  /** 是否支持批量选择 */
  enableBatchSelection?: boolean;
  /** 选中的工作流列表 */
  selectedWorkflows?: WorkflowTemplate[];
  /** 选择变化回调 */
  onSelectionChange?: (workflows: WorkflowTemplate[]) => void;
}

/**
 * 工作流列表组件
 */
export const WorkflowList: React.FC<WorkflowListProps> = ({
  onSelectWorkflow,
  onExecuteWorkflow,
  onEditWorkflow,
  showManagement = false,
  enableBatchSelection = false,
  selectedWorkflows = [],
  onSelectionChange
}) => {
  const [workflows, setWorkflows] = useState<WorkflowTemplate[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedCategory, setSelectedCategory] = useState<string>('');
  const [selectedType, setSelectedType] = useState<string>('');

  // 批量选择处理函数
  const handleSelectAll = (checked: boolean) => {
    if (!enableBatchSelection || !onSelectionChange) return;

    if (checked) {
      onSelectionChange(filteredWorkflows);
    } else {
      onSelectionChange([]);
    }
  };

  const handleSelectWorkflow = (workflow: WorkflowTemplate, checked: boolean) => {
    if (!enableBatchSelection || !onSelectionChange) return;

    if (checked) {
      onSelectionChange([...selectedWorkflows, workflow]);
    } else {
      onSelectionChange(selectedWorkflows.filter(w => w.id !== workflow.id));
    }
  };

  const isWorkflowSelected = (workflow: WorkflowTemplate) => {
    return selectedWorkflows.some(w => w.id === workflow.id);
  };

  // 删除工作流
  const handleDeleteWorkflow = async (workflow: WorkflowTemplate) => {
    if (!confirm(`确定要删除工作流 "${workflow.name}" 吗？此操作不可撤销。`)) {
      return;
    }

    try {
      await invoke('delete_workflow_template', { id: workflow.id });

      // 从列表中移除已删除的工作流
      setWorkflows(prev => prev.filter(w => w.id !== workflow.id));

      // 如果在批量选择中，也要移除
      if (enableBatchSelection && onSelectionChange) {
        onSelectionChange(selectedWorkflows.filter(w => w.id !== workflow.id));
      }
    } catch (error) {
      console.error('删除工作流失败:', error);
      setError(`删除工作流失败: ${error}`);
    }
  };

  // 加载工作流列表
  const loadWorkflows = async () => {
    try {
      setLoading(true);
      setError(null);
      
      const result = await invoke<WorkflowTemplate[]>('get_workflow_templates', {
        filter: {
          is_active: true,
          is_published: true,
          category: selectedCategory || undefined,
          workflow_type: selectedType || undefined
        }
      });
      
      setWorkflows(result);
    } catch (err) {
      console.error('加载工作流失败:', err);
      setError('加载工作流失败');
    } finally {
      setLoading(false);
    }
  };

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

  // 过滤工作流
  const filteredWorkflows = workflows.filter(workflow => {
    const matchesSearch = !searchTerm || 
      workflow.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
      workflow.description?.toLowerCase().includes(searchTerm.toLowerCase());
    
    return matchesSearch;
  });

  // 获取所有分类
  const categories = Array.from(new Set(workflows.map(w => w.category).filter(Boolean)));
  
  // 获取所有类型
  const types = Array.from(new Set(workflows.map(w => w.type)));

  // 工作流类型显示名称映射
  const typeDisplayNames: Record<string, string> = {
    outfit_generation: '穿搭生成',
    background_replacement: '背景替换',
    portrait_enhancement: '人像美化',
    image_upscaling: '图片放大',
    style_transfer: '风格转换'
  };

  // 渲染工作流卡片
  const renderWorkflowCard = (workflow: WorkflowTemplate) => (
    <div
      key={workflow.id}
      className={`bg-white rounded-lg shadow-md border-2 hover:shadow-lg transition-all p-6 ${
        enableBatchSelection && isWorkflowSelected(workflow)
          ? 'border-blue-500 bg-blue-50'
          : 'border-gray-200'
      }`}
    >
      <div className="flex justify-between items-start mb-4">
        <div className="flex items-start space-x-3 flex-1">
          {enableBatchSelection && (
            <input
              type="checkbox"
              checked={isWorkflowSelected(workflow)}
              onChange={(e) => handleSelectWorkflow(workflow, e.target.checked)}
              className="mt-1 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
            />
          )}
          <div className="flex-1">
            <h3 className="text-lg font-semibold text-gray-900 mb-1">
              {workflow.name}
            </h3>
          <div className="flex items-center space-x-2 mb-2">
            <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
              {typeDisplayNames[workflow.type] || workflow.type}
            </span>
            <span className="text-xs text-gray-500">v{workflow.version}</span>
          </div>
          {workflow.description && (
            <p className="text-sm text-gray-600 mb-3 line-clamp-2">
              {workflow.description}
            </p>
          )}
          </div>
        </div>
      </div>

      <div className="flex items-center justify-between">
        <div className="flex items-center space-x-2 text-xs text-gray-500">
          {workflow.category && (
            <span className="bg-gray-100 px-2 py-1 rounded">
              {workflow.category}
            </span>
          )}
          {workflow.author && (
            <span>作者: {workflow.author}</span>
          )}
        </div>

        <div className="flex items-center space-x-2">
          <button
            onClick={() => onSelectWorkflow?.(workflow)}
            className="p-2 text-gray-600 hover:text-blue-600 hover:bg-blue-50 rounded-lg transition-colors"
            title="查看详情"
          >
            <Eye className="w-4 h-4" />
          </button>
          
          <button
            onClick={() => onExecuteWorkflow?.(workflow)}
            className="p-2 text-white bg-blue-600 hover:bg-blue-700 rounded-lg transition-colors"
            title="执行工作流"
          >
            <Play className="w-4 h-4" />
          </button>

          {showManagement && (
            <>
              <button
                onClick={() => onEditWorkflow?.(workflow)}
                className="p-2 text-gray-600 hover:text-green-600 hover:bg-green-50 rounded-lg transition-colors"
                title="编辑工作流"
              >
                <Edit className="w-4 h-4" />
              </button>
              
              <button
                onClick={() => handleDeleteWorkflow(workflow)}
                className="p-2 text-gray-600 hover:text-red-600 hover:bg-red-50 rounded-lg transition-colors"
                title="删除工作流"
              >
                <Trash2 className="w-4 h-4" />
              </button>
            </>
          )}
        </div>
      </div>

      {workflow.tags && workflow.tags.length > 0 && (
        <div className="mt-3 pt-3 border-t border-gray-100">
          <div className="flex flex-wrap gap-1">
            {workflow.tags.map(tag => (
              <span
                key={tag}
                className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-gray-100 text-gray-800"
              >
                {tag}
              </span>
            ))}
          </div>
        </div>
      )}
    </div>
  );

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-center">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto mb-2"></div>
          <p className="text-gray-600">加载工作流中...</p>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-center">
          <p className="text-red-600 mb-2">{error}</p>
          <button
            onClick={loadWorkflows}
            className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
          >
            重试
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* 搜索和筛选栏 */}
      <div className="flex flex-col sm:flex-row gap-4">
        {enableBatchSelection && (
          <div className="flex items-center space-x-2">
            <input
              type="checkbox"
              checked={selectedWorkflows.length === filteredWorkflows.length && filteredWorkflows.length > 0}
              onChange={(e) => handleSelectAll(e.target.checked)}
              className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
            />
            <span className="text-sm text-gray-700">
              全选 ({selectedWorkflows.length}/{filteredWorkflows.length})
            </span>
          </div>
        )}

        <div className="flex-1 relative">
          <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
          <input
            type="text"
            placeholder="搜索工作流..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
          />
        </div>

        <select
          value={selectedCategory}
          onChange={(e) => setSelectedCategory(e.target.value)}
          className="px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
        >
          <option value="">所有分类</option>
          {categories.map(category => (
            <option key={category} value={category}>{category}</option>
          ))}
        </select>

        <select
          value={selectedType}
          onChange={(e) => setSelectedType(e.target.value)}
          className="px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
        >
          <option value="">所有类型</option>
          {types.map(type => (
            <option key={type} value={type}>
              {typeDisplayNames[type] || type}
            </option>
          ))}
        </select>
      </div>

      {/* 工作流列表 */}
      {filteredWorkflows.length === 0 ? (
        <div className="text-center py-12">
          <div className="text-gray-400 mb-2">
            <Filter className="w-12 h-12 mx-auto" />
          </div>
          <p className="text-gray-600">没有找到匹配的工作流</p>
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {filteredWorkflows.map(renderWorkflowCard)}
        </div>
      )}
    </div>
  );
};
