import { Element, useEditor } from '@craftjs/core';
import { Layers } from "@craftjs/layers";
import { Button, Col, Row, Tabs, TabsProps } from 'antd';
import React, { useEffect, useState } from 'react';
import { getRegisteredComponentIds, registerComponentsFromDir } from './componentRegistry';
import styles from './styles.module.less';
import styled from "styled-components";
import { AppstoreOutlined, UnorderedListOutlined } from '@ant-design/icons';
interface ComponentWrapperType extends React.FC<any> {
  craft?: {
    props?: Record<string, any>;
    displayName?: string;
  };
  componentId?: string;
  componentType?: string;
}
const TabPanelStyle = styled.div`

  height: 100%;
 .ant-tabs-tabpane{
  padding-left: 0 !important;
 }
`;

const CelStyle = styled.div`
  line-height: 36px;
  text-align: center;
  height: 36px;
  margin: 0 8px 12px 8px;
  padding: 0 12px;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  cursor: pointer;
  background: #fff;
  color: #444;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.2s ease;
  position: relative;
  z-index: 1;
  box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  &:hover {
    z-index: 2;
    transform: translateY(-1px);
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
    border-color: #1677ff;
    color: #1677ff;
    background: #f5f9ff;
  }

  &:active {
    transform: translateY(0);
    box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  }
`;

const LayersStyle = styled.div`
  height: 100%;
  width: 100%;
  overflow: auto;
  padding:10px 8px 0 8px;

  h2 {
    margin-bottom: 0;
  }

  .craft-layer-node {
    width: 100%;
  }
`;

const ComponentsGrid = styled.div`
  height: calc(100% - 40px);
  overflow-y: auto;
  padding: 8px;
`;
// 工具栏
export const ToolBox = () => {
  const {
    connectors: { create },
    actions: { setOptions, clearEvents },
    query: { getOptions }
  } = useEditor();

  const [components, setComponents] = useState<string[]>([]);
  const [componentWrappers, setComponentWrappers] = useState<Record<string, ComponentWrapperType>>({});

  useEffect(() => {
    initComponents()
  }, []);

  const initComponents = async () => {
    const optionsData = getOptions()
    const componentsList = await registerComponentsFromDir()
    setComponents(getRegisteredComponentIds())
    setComponentWrappers(componentsList as Record<string, ComponentWrapperType>);
    setOptions((options) => {
      options.resolver = { ...optionsData.resolver, ...componentsList }
    });
    clearEvents()
  }
    // 获取d.ts文件
    const handleGetDtsFile = () => {
      fetch('/api/files/types', {
        method: 'GET',
      })
        .then(response => response.json()).then(data => {
          console.log('data', data)
        })
    }
  const items: TabsProps['items'] = [
    {
      key: '1',
      label: <AppstoreOutlined style={{ fontSize: '18px' }} />,
      children: (
        <div style={{
          padding: '8px'
        }}>
        <Row gutter={[10, 10]} justify={'start'}>
        {components.length > 0 && components.map((componentId) => {
          // 获取特定组件类型
          // 尝试找到正确的组件
          const ComponentToUse = componentWrappers[componentId];
          if (!ComponentToUse) {
            console.error(`未找到组件 ID: ${componentId}。可用组件:`, Object.keys(componentWrappers));
            return null;
          }
          return (
            <Col span={12} key={componentId} >
              <Button
               className={styles.toolBoxBtn}
                block
                ref={(dom) => {
                  if (dom) {
                    try {
                      if (ComponentToUse.componentType === 'container') {
                        const element = <Element
                          {...(ComponentToUse.craft?.props || {})}
                          is={ComponentToUse}
                          canvas
                          padding={20}
                        />

                        return create(dom, element);
                      }
                      const element = <ComponentToUse
                        {...(ComponentToUse.craft?.props || {})}
                      />
                      return create(dom, element);
                    } catch (error) {
                      console.error(`创建组件错误: ${componentId}`, error);
                    }
                  }
                }}
              >
                {componentId}
              </Button>
            </Col>
          );
        })}
        <Button onClick={handleGetDtsFile}>获取d.ts文件</Button>
      </Row>
      </div>
      ),
    },
    {
      key: '2',
      label: <UnorderedListOutlined style={{ fontSize: '18px' }} />,
      children: (
        <LayersStyle>
          <Layers />
        </LayersStyle>
      ),
    },
  ];
  return (
      <div style={{
      height: '100%',
      borderRight: '1px solid #d3d3d3',
      boxSizing: 'border-box',

    }}>
      <TabPanelStyle>

      <Tabs
        tabPosition="left"
        items={items}
        style={{ height: '100%' }}
        tabBarGutter={0}
        tabBarStyle={{
          paddingTop:'20px'
        }}
      />
      </TabPanelStyle>
      
    </div>
  );
}; 