import React, { useState, useRef, useEffect, useMemo } from 'react';
import styles from './index.less';
import EasyvButton from 'components/EasyvButton';
import { Space } from '@easyv/antd';
import { Collapse } from '@easyv/react-gui';
import { PlusOutlined, EditOutlined, DeleteSquareOutlined } from '@easyv/react-icons';
import { Type } from 'models/theme.types';
import EasyvModal from 'components/EasyvModal';
import { ConfirmRef } from 'components/EasyvModal/Confirm';
import EasyvNoData from 'components/EasyvNoData';
import { ThemeType } from 'models/theme.types';
import classNames from 'classnames';
import message from 'components/message';
import { useDispatch } from 'react-redux';
import { getThemesConfig } from 'models/theme';
import { deleteThemeByIdList } from 'services/theme';
import defaultThemeIcon from 'images/icon_upload.svg';

import EditeTheme from './EditeTheme';
import EditeThemeName from './EditeThemeName';
import EasyvTooltip from 'components/EasyvTooltip';
import { getInitthemeConfigByType } from 'components/EasyvEditTheme';
import { ThemeConfigType } from 'models/theme.types';

const { Confirm } = EasyvModal;

const config = [
  {
    name: '系统主题',
    type: Type.SYSTEM,
  },
  {
    name: '自定义主题',
    type: Type.USER,
  },
];

function ThemePackage({
  onClose,
  onChange,
  onEditeThemeChange,
  onResetComponentsThemeConfig,
  onOk,
  themeConfigList,
  visible,
}: {
  themeConfigList: ThemeType[];
  visible: boolean;
  onClose: () => void;
  onResetComponentsThemeConfig: () => void;
  onEditeThemeChange?: (themeConfig: ThemeConfigType) => void;
  onOk: (id: number) => void;
  onChange: (id: number) => void;
}) {
  const dispatch = useDispatch();
  const [themeId, setThemeId] = useState(0);
  const ref = useRef<ConfirmRef>(null);
  const delRef = useRef<ConfirmRef>(null);
  const [themeVisible, setThemeVisible] = useState(false);
  const [collapsed, setCollapsed] = useState<Type[]>(config.map((d) => d.type));

  const [curEditThemeConfig, setCurEditThemeConfig] = useState(getInitthemeConfigByType(Type.USER)); //当前编辑的主题配置信息

  const [model, setModel] = useState<'add' | 'edit'>('edit');

  useEffect(() => {
    onChange?.(themeId);
  }, [themeId]);

  useEffect(() => {
    !visible && setThemeId(0);
  }, [visible]);

  themeConfigList = useMemo(() => {
    return themeConfigList.sort((a, b) => +new Date(b.updatedAt) - +new Date(a.updatedAt));
  }, [themeConfigList]);

  const onDelCancel = () => {
    delRef.current?.close();
  };

  const onDelOK = async () => {
    const hide = message.loading('主题删除中...');
    const result = await deleteThemeByIdList(curEditThemeConfig.id!);
    if (result) {
      message.success('删除成功');
      dispatch(getThemesConfig());
      onDelCancel();
    } else {
      message.error('删除失败');
    }
    hide();
  };

  const filterThemeListByType = (themeList: ThemeType[] = [], type: Type) => {
    return themeList.filter((d) => d.type === type);
  };

  const onEditeTheme = (args: ThemeConfigType) => {
    themeVisible && onEditeThemeChange?.(args);
  };

  return (
    <div className={styles.themePackage}>
      <span style={{ display: themeVisible ? 'block' : 'none', height: '100%' }}>
        <EditeTheme
          closeModal={(id) => {
            id && setThemeId(id);
            setThemeVisible(false);
          }}
          type={Type.USER}
          visible={themeVisible}
          onChange={onEditeTheme}
          model={model}
          onCancel={() => {
            setThemeVisible(false);
            // 如果选中主题，就应用当前主题色，反之回滚到默认
            themeId ? onChange?.(themeId) : onResetComponentsThemeConfig();
          }}
          curEditThemeConfig={curEditThemeConfig}
        />
      </span>
      <span style={{ display: !themeVisible ? 'block' : 'none', height: '100%' }}>
        <div className={styles.themeBox} style={{ display: 'flex' }}>
          <div className={styles.mainContent}>
            {config.map((d) => (
              <Collapse
                key={d.type}
                className={classNames(styles.collapse, {
                  [styles.collapseAction]: collapsed.includes(d.type),
                })}
                onChange={() => {
                  const _collapsed = Array.from(
                    new Set(
                      collapsed?.includes(d.type)
                        ? collapsed.filter((type) => d.type !== type)
                        : [...collapsed, d.type],
                    ),
                  );
                  setCollapsed(_collapsed);
                }}
                collapsed={collapsed ? !collapsed.includes(d.type) : true}
                bordered={false}
                header={
                  <span>{Type.USER === d.type ? <span id="custom">{d.name}</span> : d.name}</span>
                }>
                <div className={styles.colors}>
                  {themeConfigList?.length &&
                  filterThemeListByType(themeConfigList, d.type).length ? (
                    filterThemeListByType(themeConfigList, d.type).map((e) => (
                      <div
                        key={e.id}
                        className={classNames(styles.themeItem, {
                          [styles.action]: themeId === e.id,
                        })}>
                        <div className={styles.title}>
                          <EditeThemeName className={styles.name} themeConfig={e} />
                          {Type.USER === d.type && (
                            <div className={styles.icons}>
                              <EasyvTooltip placement="top" title="编辑">
                                <EditOutlined
                                  onClick={() => {
                                    setModel('edit');
                                    setCurEditThemeConfig(e);
                                    setThemeVisible(true);
                                  }}
                                />
                              </EasyvTooltip>
                              <EasyvTooltip placement="top" title="删除">
                                <DeleteSquareOutlined
                                  onClick={() => {
                                    setCurEditThemeConfig(e);
                                    delRef.current?.show();
                                  }}
                                />
                              </EasyvTooltip>
                            </div>
                          )}
                        </div>
                        <ul
                          className={styles.item}
                          style={{ backgroundColor: e.config.bgColor }}
                          onClick={() => {
                            setThemeId(e.id);
                          }}>
                          {e.config.palette.map((color) => (
                            <li key={color} style={{ backgroundColor: color }} title={color} />
                          ))}
                        </ul>
                      </div>
                    ))
                  ) : (
                    <div className={styles.noData}>
                      <EasyvNoData
                        style={{ fontSize: '12px' }}
                        text="暂无自定义主题，快去新建吧~"
                        icon={defaultThemeIcon}
                      />
                    </div>
                  )}
                </div>
              </Collapse>
            ))}
          </div>
          <div className={styles.positionFooter}>
            <div className={styles.themeButton}>
              <EasyvButton
                onClick={() => {
                  setModel('add');
                  setThemeVisible(true);
                  setCurEditThemeConfig(getInitthemeConfigByType(Type.USER));
                }}
                style={{ borderRadius: '4px' }}
                icon={<PlusOutlined className={styles.icon} />}
                theme="ghost">
                自定义主题
              </EasyvButton>
            </div>
            <div className={styles.footer}>
              <Space>
                <EasyvButton onClick={onClose}>取消</EasyvButton>
                <EasyvButton
                  theme="primary"
                  disabled={!themeId}
                  onClick={() => ref.current?.show()}>
                  确认应用
                </EasyvButton>
              </Space>
            </div>
          </div>
        </div>
      </span>

      <Confirm
        ref={ref}
        onOk={() => {
          onOk?.(themeId);
        }}
        onOkBtnType="primary"
        destroyOnClose
        title="主题包的应用将修改组件样式与可视化应用背景色"
        content="这将花费一些时间，过程如有中断主题包将不被完全应用"
      />
      <Confirm
        ref={delRef}
        onCancel={onDelCancel}
        onOk={onDelOK}
        destroyOnClose
        onOkBtnType="primary"
        title="删除确认"
        content="此操作执行不可逆，确认删除吗？"
      />
    </div>
  );
}

export default ThemePackage;
