import { h, FunctionalComponent } from 'preact';
import { useState, useEffect } from 'preact/hooks';

import { useCountDown, transformTime } from '../common/hooks/use-count-down';

import styles from './css/index.less';


export interface MatchCountdownProps {
  /** 目标时间戳（毫秒） */
  targetTime: number;
  /** 倒计时结束回调 */
  onTimeEnd?: () => void;
  /** 自定义样式类名 */
  className?: string;
}

interface FlipDigitProps {
  current: number;
  next: number;
}

// 单个数字翻动组件
const FlipDigit: FunctionalComponent<FlipDigitProps> = ({ current, next }: {
  current: string|number;
  next: string|number;
}) => {
  const [isAnimating, setIsAnimating] = useState(false);
  const [displayValue, setDisplayValue] = useState(current);

  useEffect(() => {
    if (current !== next) {
      setIsAnimating(true);
      const timer = setTimeout(() => {
        setDisplayValue(next);

        // 必须加这个，否则，真机闪烁
        setTimeout(() => {
          setIsAnimating(false);
        });
      }, 500);
      return () => clearTimeout(timer);
    }
    setDisplayValue(next);
  }, [current, next]);

  return (
    <div className={styles['pmg-flip-digit']}>
      <div className={styles['pmg-digit-wrapper']}>
        {/* 当前数字 */}
        <text className={`${styles['pmg-digit']} ${isAnimating ? styles['pmg-digit-out'] : ''}`}>
          {displayValue}
        </text>
        {/* 下一个数字 */}
        {isAnimating && (
          <text className={`${styles['pmg-digit']} ${styles['pmg-digit-in']}`}>
            {next}
          </text>
        )}
      </div>
    </div>
  );
};

const MatchCountdown = ({
  onTimeEnd,
  className = '',
  execMatchTime,
}: {
  execMatchTime?: number;
  targetTime?: number;
  onTimeEnd?: () => void;
  className?: string
}) => {
  const {
    timeData,
    remainTime,
    isFinished,
  } = useCountDown({
    ascending: true,
    autoStart: true,
    format: '',
    time: (execMatchTime
      && typeof execMatchTime === 'number')
      ? Date.now() - execMatchTime * 1000
      : 0,
  });

  if (isFinished) {
    onTimeEnd?.();
  }

  const previousTimes = transformTime(remainTime - 1000, '');
  const { timeData: previousTimeData } = previousTimes;
  const curTimeData = timeData || { hours: 0, minutes: 0, seconds: 0 } ;


  // 拆分数字
  const h1 = Math.floor(curTimeData.hours / 10);
  const h2 = curTimeData.hours % 10;
  const m1 = Math.floor(curTimeData.minutes / 10);
  const m2 = curTimeData.minutes % 10;
  const s1 = Math.floor(curTimeData.seconds / 10);
  const s2 = curTimeData.seconds % 10;

  const prevH1 = Math.floor(previousTimeData.hours / 10);
  const prevH2 = previousTimeData.hours % 10;
  const prevM1 = Math.floor(previousTimeData.minutes / 10);
  const prevM2 = previousTimeData.minutes % 10;
  const prevS1 = Math.floor(previousTimeData.seconds / 10);
  const prevS2 = previousTimeData.seconds % 10;

  return (
    <div className={`${styles['pmg-countdown']} ${className}`}>
      {/* 时 */}
      <FlipDigit
        current={prevH1}
        next={h1}
      />
      <FlipDigit
        current={prevH2}
        next={h2}
      />

      <text className={styles['pmg-separator']}>:</text>

      {/* 分 */}
      <FlipDigit
        current={prevM1}
        next={m1}
      />
      <FlipDigit
        current={prevM2}
        next={m2}
      />

      <text className={styles['pmg-separator']}>:</text>

      {/* 秒 */}
      <FlipDigit
        current={prevS1}
        next={s1}
      />
      <FlipDigit
        current={prevS2}
        next={s2}
      />
    </div>
  );
};

export default MatchCountdown;
