"use client";

import Image from "next/image";
import ReactAudioPlayer from "react-audio-player";
import {useEffect, useState} from "react";

export default function RecordBox() {
  let player: ReactAudioPlayer | null = null;
  let notes: HTMLImageElement | null = null;

  const [firstSong, setFirstSong] = useState<string | undefined>();

  useEffect(() => {
    setFirstSong(randomSong());
  }, []);

  return <div>
    <Image
      className="hidden bottom-23 right-0 fixed z-50 pb-2 pr-2"
      alt={"It's Playing"} width={100} height={100} src={"/musical_notes_final.gif"}
      unoptimized={true}
      ref={(ref) => { notes = ref; }}
    />
    <button>
      <Image className="bottom-0 right-0 fixed z-50 pb-2 pr-2 cursor-pointer"
             src={"/record_player.svg"} width={100} height={100} alt={"Player"}
             onClick={() => {
               if (player != null && notes != null) {
                 if (player.audioEl.current.paused) {
                   player.audioEl.current.play().then();
                   notes.className = "bottom-23 right-0 fixed z-50 pb-2 pr-2";
                 } else {
                   player.audioEl.current.pause();
                   notes.className = "hidden bottom-23 right-0 fixed z-50 pb-2 pr-2";
                 }
               }
             }}
      />
    </button>
    <ReactAudioPlayer
      autoPlay={true} controls={false} className=""
      volume={0.2}
      ref={(element) => { player = element; }}
      src={firstSong}
      onPlay={() => {started(player, notes)}}
      onEnded={() => {ended(player, notes)}}
      onPause={() => {stopped(player, notes)}}
    />
  </div>
}

function started(player: ReactAudioPlayer | null, notes: HTMLImageElement | null) {
  if (player != null && notes != null) {
    notes.className = "bottom-23 right-0 fixed z-50 pb-2 pr-2";
  }
}

function stopped(player: ReactAudioPlayer | null, notes: HTMLImageElement | null) {
  if (player != null && notes != null) {
    notes.className = "hidden bottom-23 right-0 fixed z-50 pb-2 pr-2";
  }
}

function ended(player: ReactAudioPlayer | null, notes: HTMLImageElement | null) {
  if (player != null && notes != null) {
    notes.className = "hidden bottom-23 right-0 fixed z-50 pb-2 pr-2";
    player.audioEl.current.src = randomSong();
    player.audioEl.current.play().then();
  }
}

function randomSong(): string {
  const rand = Math.floor(Math.random() * 9);
  let path = "/songs/";

  if (rand == 0) {
    path += "blood"
  }
  if (rand == 1) {
    path += "dna"
  }
  if (rand == 2) {
    path += "duckworth"
  }
  if (rand == 3) {
    path += "fear"
  }
  if (rand == 4) {
    path += "feel"
  }
  if (rand == 5) {
    path += "god"
  }
  if (rand == 6) {
    path += "humble"
  }
  if (rand == 7) {
    path += "xxx"
  }
  if (rand == 8) {
    path += "yah"
  }

  path += "_instrumental.mp3";

  return path;
}