import { Popover } from '@tingwujs/design';
import React, { useCallback, useMemo } from 'react';

import './PlayerRate.less';

interface iPlayerRateProps {
  speed: number; // 当前倍率
  onSpeedChange: (rate: number) => void; // 切换速率
  speedList?: number[]; // 倍率列表
  isLoading?: boolean; // 是否加载中
}

// 播放器速率选择
const PlayerRate: React.FC<iPlayerRateProps> = (props) => {
  const {
    speed,
    onSpeedChange,
    isLoading = false,
    speedList = [0.75, 1, 1.25, 1.5, 2].reverse(),
  } = props;

  // 显隐控制
  const [, setRateListVisible] = React.useState<boolean>(false);
  // 速率点击
  const handleClickRate = useCallback(
    (rate: number) => {
      onSpeedChange(rate);
      setRateListVisible(false);
    },
    [onSpeedChange],
  );

  // 渲染列表内容
  const renderPlayerRateContent = useMemo(() => {
    return (
      <div className="PlayerRate-Content">
        {speedList?.map((item: number) => {
          return (
            <div
              key={item}
              className={`select_item ${speed === item && 'select_active'}`}
              onClick={() => {
                handleClickRate(item);
              }}
            >
              {item}x
            </div>
          );
        })}
      </div>
    );
  }, [speed, speedList, handleClickRate]);

  if (isLoading) {
    return (
      <div
        className={`speed ${isLoading && 'docAudioloading'}`}
        style={{ userSelect: 'none' }}
        onMouseEnter={() => {
          setRateListVisible(true);
        }}
        onMouseLeave={() => {
          setRateListVisible(false);
        }}
      >
        {!speed || speed === 1 ? '倍速' : `${speed}x`}
      </div>
    );
  }

  return (
    <Popover
      className="PlayerRate"
      placement="top"
      arrow={false}
      overlayStyle={{ zIndex: 99 }}
      overlayInnerStyle={{ padding: 4 }}
      content={renderPlayerRateContent}
      getPopupContainer={(triggerNode) => triggerNode.parentElement as any}
      // visible={rateListVisible}
    >
      <div
        className={`speed ${isLoading && 'docAudioloading'}`}
        style={{ userSelect: 'none' }}
        onMouseEnter={() => {
          setRateListVisible(true);
        }}
        onMouseLeave={() => {
          setRateListVisible(false);
        }}
      >
        {!speed || speed === 1 ? '倍速' : `${speed}x`}
      </div>
    </Popover>
  );
};

const memoPlayerRate = React.memo(PlayerRate);
export { memoPlayerRate as PlayerRate };
