/**
 * 左侧组件面板
 * 显示可拖拽的表单组件列表
 */

import React from 'react';
import { useDraggable } from '@dnd-kit/core';
import { CSS } from '@dnd-kit/utilities';
import { Collapse, Typography } from 'antd';
import type { ComponentMeta } from '../config';
import { getComponentsByCategory } from '../config';
import '../styles.css';

const { Text } = Typography;

// 可拖拽组件项
const DraggableComponent: React.FC<{ component: ComponentMeta }> = ({ component }) => {
  const { attributes, listeners, setNodeRef, transform } = useDraggable({
    id: `new-${component.type}`,
    data: {
      type: component.type,
      isNew: true,
    },
  });

  const style = {
    transform: CSS.Translate.toString(transform),
    cursor: 'move',
  };

  const Icon = component.icon;

  return (
    <div
      ref={setNodeRef}
      style={style}
      {...listeners}
      {...attributes}
      className="form-designer-component-item"
    >
      <Icon style={{ marginRight: 6, fontSize: 14, flexShrink: 0 }} />
      <Text style={{ fontSize: 12 }}>{component.label}</Text>
    </div>
  );
};

interface ComponentPanelProps {
  extraComponents?: ComponentMeta[]; // 额外的组件（如工作流扩展字段）
}

// 组件面板
const ComponentPanel: React.FC<ComponentPanelProps> = ({ extraComponents = [] }) => {
  const coreComponents = getComponentsByCategory();

  // 合并核心组件和扩展组件
  const allComponents = React.useMemo(() => {
    const merged = { ...coreComponents };
    
    extraComponents.forEach(comp => {
      if (!merged[comp.category]) {
        merged[comp.category] = [];
      }
      merged[comp.category].push(comp);
    });
    
    return merged;
  }, [coreComponents, extraComponents]);

  // 定义分类显示顺序
  const categoryOrder = ['布局字段', '基础字段', '高级字段'];

  return (
    <div className="form-designer-component-panel">
      <div className="form-designer-component-panel-header">
        <Text strong>组件列表</Text>
      </div>
      
      <div className="form-designer-component-panel-body">
        <Collapse 
          defaultActiveKey={['基础字段', '高级字段', '布局字段']} 
          ghost
          bordered={false}
          items={categoryOrder
            .map((category) => {
              const components = allComponents[category];
              if (!components || components.length === 0) return null;
              
              return {
                key: category,
                label: category,
                children: (
                  <div className="form-designer-component-list">
                    {components.map((component) => (
                      <DraggableComponent key={component.type} component={component} />
                    ))}
                  </div>
                ),
              };
            })
            .filter(Boolean) as any[]
          }
        />
      </div>
    </div>
  );
};

export default ComponentPanel;

