import React from 'react';
import { Modal, message, Form, Input } from 'antd';
import { AssetTypeEnum, AssetFromTypeEnum, EasyTwinRenderer, AssetInfo } from '@easytwin/core';

import { AssetTypeInfos } from '@/constants';
import { initStateData } from '@/server';
import { useAsset } from '@/pages/AssetManage/module';
import PointForm from './PointForm';

const ConatinerId = 'scene-editor-asset-preview';

export interface CreateAssetModalProp {
  assetType: AssetTypeEnum;
  onOk?: () => void;
  onCancel?: () => void;
}

const CreateAssetModal: React.FC<CreateAssetModalProp> = function ({ assetType, onOk, onCancel }) {
  const [easyTwinRenderer, setEasyTwinRenderer] = React.useState<EasyTwinRenderer>();
  React.useEffect(() => {
    const containerDom = document.getElementById(ConatinerId);
    if (containerDom !== null && !easyTwinRenderer) {
      const renderer = new EasyTwinRenderer({
        containerId: ConatinerId,
        viewHelper: {
          enable: false,
        },
        sceneOption: {
          baseMap: {
            id: '',
            gridDivisions: 10,
            gridSize: 100,
          },
        },
      });
      // renderer.setViewMode('preview');

      renderer.setViewPortAttr({
        position: {
          x: 9.210537265932397,
          y: 53.52942999449814,
          z: 113.4078818177321,
        },
        target: {
          x: -0.44100432190687655,
          y: 0.07331391781344612,
          z: 0.034559999988506264,
        },
      });
      setEasyTwinRenderer(renderer);
    }

    return () => {
      if (easyTwinRenderer) {
        easyTwinRenderer.disposeViewport();
        setEasyTwinRenderer(undefined);
      }
    };
  }, [easyTwinRenderer]);

  const assetSuffix = React.useMemo(
    () => AssetTypeInfos.find((i) => i.type === assetType)?.label,
    [assetType],
  );

  const [form] = Form.useForm();
  const [baseFormData, setBaseFormData] = React.useState<Pick<AssetInfo, 'name'>>();

  const { createAsset } = useAsset();
  const [createAssetData, setCreateAssetData] = React.useState<Pick<AssetInfo, 'config'>>();

  const formRender = () => {
    const props = {
      initData: initStateData[assetType],
      easyTwinRenderer,
      onValuesChanges: setCreateAssetData,
    };

    switch (assetType) {
      case AssetTypeEnum.POINT:
        return <PointForm {...props} />;
      default:
        return null;
    }
  };

  const handleOk = async () => {
    if (!baseFormData?.name || !createAssetData) return;

    await createAsset({
      name: `${baseFormData.name}${assetSuffix}`,
      type: assetType,
      config: createAssetData.config,
      description: '',
      thumb: '',
      // TODO: 需要获取 categoryId
      categoryId: '',
    });

    message.success('新建成功，可前往数字要素使用！');

    onOk?.();
  };

  return (
    <Modal
      visible
      title={`新建数字要素资产-${AssetTypeInfos.find((i) => i.type === assetType)?.label}`}
      width={800}
      zIndex={10001}
      okButtonProps={{
        disabled: !baseFormData?.name || !createAssetData,
      }}
      maskClosable={false}
      onOk={handleOk}
      onCancel={onCancel}>
      <div className="h-80 flex gap-x-4">
        <div className="w-74">
          {/*  */}
          <Form
            form={form}
            className="!px-1"
            labelCol={{
              span: 6,
            }}
            wrapperCol={{
              span: 18,
            }}
            labelAlign="left"
            colon={false}
            onValuesChange={setBaseFormData}>
            <Form.Item name="name" label="名称" className="!mb-2">
              <Input suffix={assetSuffix} />
            </Form.Item>
          </Form>

          {/*  */}
          {formRender()}
        </div>
        <div className="flex-1">
          <div id={ConatinerId} className="w-full h-full" />
        </div>
      </div>
    </Modal>
  );
};

export default CreateAssetModal;
