import {
  Component,
  h, Ref, useMemo, useRef, useState,
} from "atomico";
// eslint-disable-next-line no-unused-vars
import { Either, Left, Right } from "funfix";
import { getDurationTime } from "@caedman/spring/build/get-duration-time.esm";

import style from "./kun-audio-player.scss";
import { getComponentOrDefine } from "../../hooks/aync-hook/redirect";

function tryParseInt(str: string): Either<string, number> {
  const i = parseInt(str, 10);
  // eslint-disable-next-line no-restricted-globals
  return isNaN(i) ? Left(str) : Right(i);
}

const KunAudioPlayer = ({ url }): Component => {
  const audioRef: Ref<HTMLAudioElement> = useRef<HTMLAudioElement>();
  const [isPlaying, setPlaying] = useState(false);
  const [duration, setDuration] = useState(0);
  const [percent, setPercentage] = useState(0);

  const [currentTime, setCurrent] = useState("00:00");
  const timeAmount = useMemo(() => getDurationTime(duration), [duration]);

  const playHead = async (): Promise<void> => {
    await audioRef.current.pause();
    audioRef.current.currentTime = 0;

    await audioRef.current.play?.();
  };

  const play = async (): Promise<void> => {
    await audioRef.current.play?.();
  };

  const loadMeta = (): void => {
    const du = audioRef.current.duration;
    setDuration(du);
  };

  const stop = async (): Promise<void> => {
    await audioRef.current?.pause?.();
  };

  const timeUpdate = (): void => {
    if (audioRef?.current != null) {
      const du = audioRef.current.currentTime;
      const r = tryParseInt(((du / duration) * 100).toFixed(2));
      setPercentage(r.getOrElse(0));
      setCurrent(getDurationTime(du));
    }
  };

  return (
    <host>
      <style>{style}</style>
      <div>
        <button type="button" onclick={async () => playHead()}>从头播放</button>
        <div class="container flex-initial flex">
          {
  isPlaying && (
  <div className="icon-play cursor-pointer" onclick={stop} role="presentation" />
  )
          }
          {

            !isPlaying && (
            <div className="icon-pause cursor-pointer" onclick={play} role="presentation" />
            )
          }

          <div className="flex-col flex w-full ml-3">
            <div className="w-full">英语</div>
            <div className="flex-row flex w-full items-center">
              <div className="flex-none mr-1">{currentTime}</div>

              <div className="line flex-1 flex-auto">
                <div className="line2" style={{ width: `${percent}%` }} />
              </div>

              <div className="flex-none ml-1">{timeAmount}</div>
            </div>
          </div>

        </div>

        <div className="main-slider" />

        <audio
          ref={audioRef}
          src={url}
          onloadedmetadata={loadMeta}
          ontimeupdate={timeUpdate}
          onplay={() => setPlaying(true)}
          onpause={() => setPlaying(false)}
        />
      </div>
    </host>
  );
};

KunAudioPlayer.props = {
  url: {
    type: String,
    value: "http://audio-pm.woshipm.com/cache/vava-3793577.mp3",
    reflect: true,
    event: {
      type: "changeMessage",
    },
  },
};

export default getComponentOrDefine("kun-audio-player", KunAudioPlayer);
