import React, { useEffect, useCallback, useState } from 'react';
import { Form, Empty, message } from 'antd';
import { PlusCircleOutlined, DeleteOutlined } from '@easyv/react-icons';
import { StateInfo, UpdateStateQuery, StateConfig, StateTypeEnum } from '@easytwin/core';
import { CollapseBox, SortableTabs, BlurInput } from '@/components';
import ProjectForm from './ProjectForm';
import ModelForm from './ModelForm';
import PointLightForm from './PointLightForm';
import DirectLightForm from './DirectLightForm';
// import PointForm from './PointForm';
// import PoiPannelForm from './PoiPannelForm';
// import PoiIframeForm from './PoiIframeForm';
// import FenceForm from './FenceForm';

export interface StateManageProp {
  showExtraBth?: boolean;
  dataSource: StateInfo[];
  type: StateTypeEnum;
  isGroup: boolean;
  selectKey?: string;
  onTabChange?: (key?: string) => void;
  onAdd?: () => void;
  onUpdate?: (state: Partial<UpdateStateQuery>) => void;
  onRemove?: (key: string) => void;
}

export default function StateManage({
  showExtraBth = true,
  dataSource,
  type,
  isGroup,
  selectKey,
  onTabChange,
  onAdd,
  onUpdate,
  onRemove,
}: StateManageProp) {
  const [form] = Form.useForm();
  const [editData, setEditData] = useState<StateInfo>();
  const [editDataConfig, setEditDataConfig] = useState<StateInfo['config']>();

  useEffect(() => {
    if (selectKey === undefined && dataSource.length > 0) {
      onTabChange?.(dataSource[0].id);
      return;
    }

    const newEditData = dataSource.find((item) => item.id === selectKey);
    if (newEditData) {
      setEditData(newEditData);
      setEditDataConfig(newEditData.config);
    }
  }, [dataSource, selectKey]);

  useEffect(() => {
    if (editData) form.setFieldsValue(editData);
  }, [editData, form]);

  const handleStateDataFormChange = useCallback(
    (updateValues: Partial<UpdateStateQuery>) => {
      if (editData) {
        onUpdate?.({
          id: editData.id,
          rank: editData.rank,
          ...updateValues,
        });
      }
    },
    [editData, onUpdate],
  );

  const handleTagDrapChange = (dragKey: string, rank: number) => {
    onUpdate?.({
      id: dragKey,
      rank,
    });
  };

  const stateDataFromRender = () => {
    if (!editDataConfig) return null;

    const props = {
      dataSource: editDataConfig,
      onChange: (value: StateConfig) => handleStateDataFormChange({ config: value }),
    };

    switch (type) {
      case StateTypeEnum.PROJECT:
        return <ProjectForm {...props} />;
      case StateTypeEnum.MODEL:
        return <ModelForm {...props} />;
      case StateTypeEnum.POINTLIGHT:
        return <PointLightForm {...props} />;
      case StateTypeEnum.DIRECTLIGHT:
        return <DirectLightForm {...props} />;
      // case StateTypeEnum.POINT:
      //   return <PointForm {...props} />;
      // case StateTypeEnum.POIPANNEL:
      //   return <PoiPannelForm {...props} isGroup={isGroup} />;
      // case StateTypeEnum.POIIFRAME:
      //   return <PoiIframeForm {...props} />;
      // case StateTypeEnum.FENCE:
      //   return <FenceForm {...props} />;
      default:
        return null;
    }
  };

  return (
    <CollapseBox
      title="状态"
      titleExtra={
        showExtraBth && (
          <>
            <PlusCircleOutlined
              className="anticon hover:text-primary p-1"
              onClick={(e) => {
                e.stopPropagation();
                onAdd?.();
              }}
            />
            <DeleteOutlined
              className="anticon hover:text-primary p-1"
              onClick={(e) => {
                e.stopPropagation();
                if (dataSource.length === 1) {
                  message.warn('状态不可全部删除，请至少保留一条状态');
                  return;
                }

                if (editData) {
                  onRemove?.(editData.id);
                }
              }}
            />
          </>
        )
      }>
      {dataSource.length ? (
        <div className="px-3 py-2">
          <div className="bg-bgColorSecondary mb-4">
            <SortableTabs
              dataSource={dataSource}
              selectKey={selectKey}
              onTabChange={onTabChange}
              onDragChange={handleTagDrapChange}
            />
          </div>
          {editData && (
            <>
              {/*  */}
              <Form
                form={form}
                className="!px-1"
                labelCol={{
                  span: 6,
                }}
                wrapperCol={{
                  span: 18,
                }}
                labelAlign="left"
                colon={false}
                onValuesChange={(_, allValues: StateInfo) => handleStateDataFormChange(allValues)}>
                {/* name */}
                {isGroup && (
                  <Form.Item name="name" label="状态名称" className="!mb-2">
                    <BlurInput />
                  </Form.Item>
                )}
              </Form>

              {stateDataFromRender()}
            </>
          )}
        </div>
      ) : (
        <Empty description="暂无状态" className="py-8" />
      )}
    </CollapseBox>
  );
}
