import { UploadOutlined } from '@ant-design/icons';
import { useEditor, Element } from '@craftjs/core';
import { Button, Col, Input, Layout, Modal, Row, Upload, UploadProps, message } from 'antd';
import React, { useEffect, useState } from 'react';
import { createBaseComponents, getRegisteredComponentIds, registerComponent, registerComponentsFromDir } from './componentRegistry';
import { Component } from '@/pages/components/BaseInput/index';
import { Settings } from '@/pages/components/BaseInput/settings';
import { toAllPascalCase, toCamelCase } from './utils';
import { Layers } from "@craftjs/layers"
const baseUrl = '/api'
interface ComponentWrapperType extends React.FC<any> {
  craft?: {
    props?: Record<string, any>;
    displayName?: string;
  };
  componentId?: string;
}

// 工具栏
export const ToolBox = () => {
  const {
    connectors: { create },
    actions: { setOptions, clearEvents },
    query: { getOptions }
  } = useEditor();

  const [components, setComponents] = useState([]);
  const [componentWrappers, setComponentWrappers] = useState<Record<string, ComponentWrapperType>>({});

  useEffect(() => {
    initComponents()
  }, []);

  const initComponents = async () => {
    const optionsData = getOptions()
    const componentsList = await registerComponentsFromDir()
    console.log('11222,componentsList', componentsList)
    setComponents(getRegisteredComponentIds())
    console.log('11222,componentsList', getRegisteredComponentIds())
    setComponentWrappers(componentsList as Record<string, ComponentWrapperType>);

    setOptions((options) => {
      options.resolver = { ...optionsData.resolver, ...componentsList }
    });
    clearEvents()
  }
  // 引入输入框组件
  const handleAddButton = () => {
    console.log('添加输入框组件');
    // Check if the component is already registered
    if (getRegisteredComponentIds().includes('input')) {
      message.info('输入框组件已经注册过了');
      return;
    }

    registerComponent('input', {
      component: Component,
      settings: Settings,
      displayName: 'Input',
      defaultProps: {
        text: '输入框',
        size: 'middle',
        placeholder: '请输入...',
      },
    });
    // Update the component list
    const data = getRegisteredComponentIds()
    setComponents(data);
    console.log('data', data)
    // Update component wrappers
    const updatedComponents = createBaseComponents();
    setComponentWrappers(updatedComponents as Record<string, ComponentWrapperType>);

    // 关键：直接通过CraftJS的setOptions更新resolver
    // 确保正确处理resolver更新，添加详细日志
    console.log('getOptions', getOptions(), updatedComponents);
    const componentName = 'inputComponentsWrapper';

    // 尝试找到正确的组件
    const ComponentsWrapper = updatedComponents[componentName];
    const optionsData = getOptions();

    setOptions((options) => {
      options.resolver = { ...optionsData.resolver, [componentName]: ComponentsWrapper }
    });
    clearEvents()
    // 同时更新context以保持状态一致性
    // updateComponents();

    // 记录组件注册后的状态
    // console.log('组件已注册:', getRegisteredComponentIds());
    console.log('更新后的组件类型:', updatedComponents);

    message.success('成功引入输入框组件');
  };
  // 引入url函数
  const loadComponent = (url: string, globalName: string) => {
    return new Promise<any>((resolve, reject) => {
      const script = document.createElement('script');
      script.src = url;
      script.type = 'module';
      script.onload = () => {
        if ((window as any)[globalName]) {
          const umdModule = (window as any)[globalName];
          // 验证UMD模块格式
          console.log(11, umdModule)
          // if (umdModule.Component && umdModule.type) {
          // 注册到组件注册表
          // registerComponent(umdModule.type, umdModule);
          message.success(`组件 ${umdModule.name || umdModule.type} 加载成功`);
          resolve(umdModule);
          // } else {
          //   reject(new Error('组件格式错误: 必须包含 component 和 type 属性'));
          // }
        } else {
          reject(new Error(`全局变量 ${globalName} 未找到`));
        }
      };
      script.onerror = () => reject(new Error(`加载脚本失败: ${url}`));
      document.head.appendChild(script);
    });
  };
  // 引入url
  const handleAddComponentUrl = () => {
    let componentUrl = 'http://localhost:5173/dist/tab-radio/index.umd.js';
    const componentType = 'tab-radio';

    Modal.confirm({
      title: '加载组件',
      content: (
        <div>
          <p>输入组件地址：</p>
          <Input
            defaultValue={componentUrl}
            onChange={(e) => componentUrl = e.target.value}
            style={{ width: '100%' }}
          />
        </div>
      ),
      onOk: async () => {
        try {
          let module = await loadComponent(componentUrl, componentType);
          console.log('res', module)
          const typeName = toAllPascalCase(componentType)
          const moduleName = module.Component ? 'Component' : typeName
          const settingsName = module.Settings ? 'Settings' : typeName + 'Settings'
          const defaultPropsName = module.defaultProps ? 'defaultProps' : toCamelCase(componentType) + 'DefaultProps'

          registerComponent(toAllPascalCase(componentType), {
            component: module[moduleName],
            settings: module[settingsName],
            displayName: toAllPascalCase(componentType),
            defaultProps: module[defaultPropsName] || {}
          });
          const data = getRegisteredComponentIds()
          setComponents(data);
          console.log('data', data)
          // Update component wrappers
          const updatedComponents = createBaseComponents();
          setComponentWrappers(updatedComponents as Record<string, ComponentWrapperType>);
          const componentName = `${typeName}`;
          console.log('getOptions', getOptions(), componentName);
          // 尝试找到正确的组件
          const ComponentsWrapper = updatedComponents[componentName];
          const optionsData = getOptions();
          setOptions((options) => {
            options.resolver = { ...optionsData.resolver, [componentName]: ComponentsWrapper }
          });
          clearEvents()
        } catch (error: any) {
          message.error(`加载组件失败: ${error.message}`);
          console.error(error);
        } finally {
        }
      }
    });
  };
  // 上传文件夹
  const uploadFolderProps: UploadProps = {
    name: 'files',
    action: `${baseUrl}/files/upload-folder`,
    data: {
      folderName: 'components',
    },
    headers: {
      authorization: 'authorization-text',
    },
    onChange(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        message.success(`${info.file.name} file uploaded successfully`);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} file upload failed.`);
      }
    },
  };
  // 上传文件
  const uploadProps: UploadProps = {
    name: 'file',
    action: `${baseUrl}/files/upload`,
    headers: {
      authorization: 'authorization-text',
    },
    onChange(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        message.success(`${info.file.name} file uploaded successfully`);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} file upload failed.`);
      }
    },
  };
  // 获取d.ts文件
  const handleGetDtsFile = () => {
    fetch(`${baseUrl}/files/types`, {
      method: 'GET',
    })
      .then(response => response.json()).then(data => {
        console.log('data', data)
      })
  }
  // 获取components文件
  const handleGetComponentsFile = () => {
    fetch('http://localhost:9090/files/components', {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      },
    })
      .then(response => response.json()).then(data => {
        console.log('data', data)
      })
  }
  return (
    <div
      style={{
        height: '100%',
        borderRight: '1px solid #9d9d9d',
        boxSizing: 'border-box',
        padding: 10,
      }}
    >
      <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
                block
                ref={(dom) => {
                  if (dom) {
                    try {
                      if (componentId === 'ComponentContainer' || componentId === 'Layout') {
                        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>
          );
        })}
      </Row>
      <Layers />
      {/* <Button
        style={{ marginTop: '10px' }}
        onClick={handleAddButton}
      >
        引入输入框组件
      </Button> */}
      <Button
        style={{ marginTop: '10px' }}
        onClick={handleAddComponentUrl}
      >
        引入url
      </Button>
      {/* <Upload directory {...uploadFolderProps}>
        <Button icon={<UploadOutlined />}>上传文件夹</Button>
      </Upload> */}
      <Upload {...uploadProps}>
        <Button icon={<UploadOutlined />} style={{ marginTop: '10px' }}>上传文件</Button>
      </Upload>
      <Button onClick={handleGetDtsFile}>获取d.ts文件</Button>
      {/* <Button onClick={handleGetComponentsFile}>获取components文件</Button> */}
    </div>
  );
}; 