import { useNavigate, useParams } from 'react-router-dom';
import { Upload, Tooltip } from 'antd';
import { debounce } from 'lodash-es';
import { useRecoilState } from 'recoil';
import {
  PreviewLightColored,
  DownloadOutlined,
  PlusOutlined,
  BulbOutlined,
  SpotLightOutlined,
  DirectionalLightOutlined,
} from '@easyv/react-icons';
import { ComponentTypeEnum, CreateComponentQuery } from '@easytwin/core';
import { BackButton, ContextMenuItem } from '@/components';
import { _globalLoadingInfo } from '@/pages/module';
import { NameEdit } from '@/pages/ProjectManage/components';
import { useProject } from '@/pages/ProjectManage/module';
import { useMutation, useQuery } from 'react-query';
import { ProjectApi } from '@/server';
import { ProjectEditorPageParams } from './module';
import { CardBotton } from './components';
import { queryClient } from '../../plugins/ReactQuery';

export interface HeaderProp {
  onUploadModelList: (value: any) => void;
  onCreateLight: (query: Pick<CreateComponentQuery, 'name' | 'type'>) => void;
  onShowOfficialModelPopup: (value: boolean) => void;
}
export default function Header({
  onUploadModelList,
  onCreateLight,
  onShowOfficialModelPopup,
}: HeaderProp) {
  const navigate = useNavigate();
  const { projectId } = useParams<ProjectEditorPageParams>();
  const { data: projectInfo } = useQuery('projectInfo', () => {
    if (projectId) {
      return ProjectApi.getProject({ id: projectId });
    }
    throw Error('缺失 projectId');
  });
  const projectMutation = useMutation(ProjectApi.updateProject, {
    onSuccess: () => {
      queryClient.invalidateQueries('projectInfo');
    },
  });
  const [, setLoadingInfo] = useRecoilState(_globalLoadingInfo);
  const { exportProject } = useProject();
  return (
    <div className="h-16 flex items-center bg-bgColorBase border border-b border-black">
      {/* left */}
      <div className="w-60 min-w-60 flex gap-x-2 items-center pl-4">
        <BackButton onClick={() => navigate('/')} />
        <div className="flex-auto pr-2">
          <NameEdit
            initValue={projectInfo?.name || null}
            onChange={(value) => {
              if (projectId) {
                projectMutation.mutate({ id: projectId, name: value });
              }
            }}
          />
        </div>
      </div>
      <div className="flex items-center flex-1">
        <Tooltip
          trigger="click"
          placement="bottomLeft"
          overlayInnerStyle={{ padding: '0px', marginTop: '4px' }}
          title={
            <div className="w-22">
              <Upload
                multiple
                accept=".fbx,.gltf,.glb"
                fileList={[]}
                showUploadList={false}
                beforeUpload={() => false}
                onChange={debounce(onUploadModelList, 100)}>
                <ContextMenuItem
                  title="本地模型"
                  icon={<SpotLightOutlined className="anticon" />}
                />
              </Upload>
              <ContextMenuItem
                title="官方模型"
                icon={<DirectionalLightOutlined className="anticon" />}
                onClick={() => {
                  onShowOfficialModelPopup(true);
                }}
              />
            </div>
          }>
          <CardBotton icon={<PlusOutlined className="anticon" />} title="模型" />
        </Tooltip>
        <Tooltip
          trigger="click"
          placement="bottomLeft"
          overlayInnerStyle={{ padding: '0px', marginTop: '4px' }}
          title={
            <div className="w-22">
              <ContextMenuItem
                title="点光源"
                icon={<SpotLightOutlined className="anticon" />}
                onClick={() =>
                  onCreateLight({ name: '点光源', type: ComponentTypeEnum.POINTLIGHT })
                }
              />
              <ContextMenuItem
                title="平行光"
                icon={<DirectionalLightOutlined className="anticon" />}
                onClick={() =>
                  onCreateLight({ name: '平行光', type: ComponentTypeEnum.DIRECTLIGHT })
                }
              />
            </div>
          }>
          <CardBotton icon={<BulbOutlined className="anticon" />} title="灯光" />
        </Tooltip>
      </div>

      {/* right */}
      <div className="flex gap-x-2 items-center pr-4">
        <CardBotton
          icon={<DownloadOutlined className="anticon text-base" />}
          title="导出"
          onClick={async () => {
            if (projectId) {
              setLoadingInfo({ loading: true, tip: '正在导出文件...' });
              await exportProject({ id: projectId });
              setLoadingInfo({ loading: false, tip: null });
            }
          }}
        />
        <CardBotton
          icon={<PreviewLightColored className="anticon text-base" />}
          title="预览"
          onClick={() =>
            navigate(
              `/project-preview/${projectId}?from=${window.location.hash.split('#').join('')}`,
            )
          }
        />
      </div>
    </div>
  );
}
