import React, { useCallback, useEffect, useRef, useState, useMemo } from 'react';
import styles from './style.less';
import {
  CloseCircleOutlined,
  CloseOutlined,
  DeleteSquareOutlined,
  InfoCircleOutlined,
} from '@easyv/react-icons';
import EasyvScrollContainer from 'components/EasyvScrollContainer';
import EasyvTooltip from '@/components/EasyvTooltip';
import { DebugDataType, DebugType } from '@/utils/debug-screen';
import ItemDebug from './ItemDebug';
import IconWrapper from '@/components/IconWrapper';
import classNames from 'classnames';
import { DebugConfigType } from '../config-container';
import LogSearchInput from './LogSearchInput';
import IFContainer from '@/components/IFContainer/IFContainer';
import EasyvEmpty from '@/components/EasyvEmpty';
type Props = {
  onClose: () => void;
  config: DebugConfigType;
  setConfig: (v: DebugConfigType) => void;
};

const LogOverview = ({
  total,
  onClear,
  errorLength,
  infoLength,
  onSearch,
}: {
  total: number;
  onClear: () => void;
  infoLength: number;
  errorLength: number;
  onSearch: (v?: DebugType) => void;
}) => {
  const [curIndex, setCurIndex] = useState<'error' | 'info'>();

  return (
    <div className={styles.contentTitle}>
      <div className={styles.contentLeft}>
        <span>日志信息 共{total}条</span>
        <div className={styles.switchIcon}>
          <EasyvTooltip title="点击筛选该类型日志" placement="top">
            <span
              onClick={() => {
                setCurIndex(curIndex === 'error' ? undefined : 'error');
                onSearch(curIndex === 'error' ? undefined : 'error');
              }}
              className={classNames(
                styles.iconSpan,
                curIndex === 'error' ? styles.selected : null,
              )}>
              <IconWrapper icon={CloseCircleOutlined} />
              {errorLength}
            </span>
          </EasyvTooltip>
          <EasyvTooltip title="点击筛选该类型日志" placement="top">
            <span
              onClick={() => {
                setCurIndex(curIndex === 'info' ? undefined : 'info');
                onSearch(curIndex === 'info' ? undefined : 'info');
              }}
              className={classNames(styles.iconSpan, curIndex === 'info' ? styles.selected : null)}>
              <IconWrapper icon={InfoCircleOutlined} />
              {infoLength}
            </span>
          </EasyvTooltip>
        </div>
      </div>
      <EasyvTooltip title="清空日志" placement="top">
        <DeleteSquareOutlined className={styles.icon} onClick={onClear} />
      </EasyvTooltip>
    </div>
  );
};

const LogContainer = (props: Props) => {
  const { onClose } = props;
  const [debugScreenInfo, setDebugScreenInfo] = useState<DebugDataType[]>([]);
  const [searchValue, setSearchValue] = useState<{
    filterComponentsId?: number[];
    curType?: DebugType;
  }>();
  const ref = useRef<HTMLDivElement>(null);

  const errorLength = useMemo(() => {
    return debugScreenInfo.filter((d) => d.type === 'error').length;
  }, [debugScreenInfo]);

  const updateCurDetail = useCallback((e: CustomEvent<DebugDataType>) => {
    setDebugScreenInfo((pre) => pre.concat(e.detail));
  }, []);

  useEffect(() => {
    // 只有在录制（监听）数据流状态才监听debugScreenEvent事件
    document.addEventListener('debugScreenEvent', updateCurDetail);
    return () => {
      document.removeEventListener('debugScreenEvent', updateCurDetail);
    };
  }, []);

  const logList = useMemo(() => {
    const { filterComponentsId = [], curType } = searchValue || {};
    if (!filterComponentsId.length)
      return curType ? debugScreenInfo.filter((d) => d.type === curType) : debugScreenInfo;
    return curType
      ? debugScreenInfo.filter((d) => filterComponentsId.includes(d.id) && d.type === curType)
      : debugScreenInfo.filter((d) => filterComponentsId.includes(d.id));
  }, [debugScreenInfo, searchValue]);

  return (
    <div className={styles.container}>
      <div className={styles.header}>
        <span>控制台</span>
        <CloseOutlined onClick={onClose} />
      </div>

      <div className={styles.content} ref={ref}>
        <LogOverview
          total={debugScreenInfo.length}
          errorLength={errorLength}
          infoLength={debugScreenInfo.length - errorLength}
          onClear={() => {
            setDebugScreenInfo([]);
          }}
          onSearch={(v) => {
            setSearchValue({ ...searchValue, curType: v });
          }}
        />
        <LogSearchInput
          onSearch={(v) => setSearchValue({ ...searchValue, filterComponentsId: v })}
        />
      </div>

      <EasyvScrollContainer
        className={styles.listContainer}
        style={{ maxHeight: `calc(100vh - 36px - ${ref.current?.clientHeight}px)` }}>
        <IFContainer
          conditional={logList.length > 0}
          thenRender={
            <>
              {logList.map((item, i) => (
                <ItemDebug {...item} key={i} />
              ))}
            </>
          }
          elseRender={
            <div
              className={styles.emptyContainer}
              style={{
                height: `calc(100vh - 36px - ${ref.current?.clientHeight}px)`,
              }}>
              <EasyvEmpty
                description={
                  searchValue?.curType || searchValue?.filterComponentsId?.length
                    ? '未找到相关内容'
                    : '无日志信息'
                }
              />
            </div>
          }
        />
      </EasyvScrollContainer>
    </div>
  );
};

export default LogContainer;
