import { Button, Grid } from "@mui/material";
import React, { useState, useEffect } from "react";
import {
  LeftTracks1000,
  LeftTracks2000,
  LeftTracks500,
  LeftTracks3000,
  LeftTracks4000,
  LeftTracks6000,
  RightTracks500,
  RightTracks1000,
  RightTracks2000,
  RightTracks3000,
  RightTracks4000,
  RightTracks6000,
  KUSU,
} from "./tunes";
import { useLocation, useNavigate, useParams } from "react-router-dom";
import CheckIcon from "@mui/icons-material/Check";
import UserResponseService from "../services/istar/UserResponseService";
// const AudioPlayer = window.ReactH5AudioPlayer.default;
import AudioPlayer from "react-h5-audio-player";
import "react-h5-audio-player/lib/styles.css";

let kusu = "http://localhost:8080/kusu.mp3";
console.log("KUSUUUUU: ", kusu);

const colorsArray = [
  "#6F1EBC",
  "#FBB03F",
  "#DDBAFF",
  "#252525",
  "#6C6C6C",
  "#EC2D2D",
  "#A9A9A9",
  "#71FF1B",
  "#FFF61B",
  "#FF1B1B",
];
const useAudio = (url) => {
  const [audio] = useState(new Audio(url));
  const [playing, setPlaying] = useState(false);
  const [isEnd, setIsEnd] = useState(false);

  const toggleEnd = () => setIsEnd(false);

  const toggle = () => setPlaying(!playing);
  console.log("VOLUME", audio.volume);
  useEffect(() => {
    playing ? audio.play() : audio.pause();
    if (playing) {
      audio.volume = 1;
    }
  }, [playing]);

  useEffect(() => {
    audio.addEventListener("ended", () => {
      setPlaying(false);
      setIsEnd(true);
      console.log("ON END", url);
    });
    return () => {
      audio.removeEventListener("ended", () => {
        console.log("removed");
        setPlaying(false);
      });
    };
  }, []);

  return [playing, toggle, isEnd, toggleEnd];
};

const Player = ({ url }) => {
  const navigate = useNavigate();
  const params = useParams();
  const location = useLocation();
  const [currentArray, setCurrentArray] = useState("RightTracks500");
  const [currentTrack, setCurrentTrack] = useState(RightTracks500[0]);
  // const [currentTrack, setCurrentTrack] = useState(KUSU);
  const [playing, toggle, isEnd, toggleEnd] = useAudio(currentTrack?.url);
  const [buttonColor, setButtonColor] = useState("#6F1EBC");
  const [colorCount, setColorCount] = useState(0);
  const [result, setResult] = useState({
    leftEar: [],
    rightEar: [],
  });

  console.log(currentTrack?.url);
  React.useEffect(() => {
    if (isEnd) {
      if (currentArray == "LeftTracks500") {
        if (currentTrack.id < 7) {
          setCurrentTrack(LeftTracks500[currentTrack.id]);
          toggle();
          toggleEnd();
        }
      } else if (currentArray == "LeftTracks1000") {
        if (currentTrack.id < 7) {
          setCurrentTrack(LeftTracks1000[currentTrack.id]);
          toggle();
          toggleEnd();
        }
      } else if (currentArray == "LeftTracks2000") {
        if (currentTrack.id < 7) {
          setCurrentTrack(LeftTracks2000[currentTrack.id]);
          toggle();
          toggleEnd();
        }
      } else if (currentArray == "LeftTracks3000") {
        if (currentTrack.id < 7) {
          setCurrentTrack(LeftTracks3000[currentTrack.id]);
          toggle();
          toggleEnd();
        }
      } else if (currentArray == "LeftTracks4000") {
        if (currentTrack.id < 7) {
          setCurrentTrack(LeftTracks4000[currentTrack.id]);
          toggle();
          toggleEnd();
        }
      } else if (currentArray == "LeftTracks6000") {
        if (currentTrack.id < 7) {
          setCurrentTrack(LeftTracks6000[currentTrack.id]);
          toggle();
          toggleEnd();
        }
      } else if (currentArray == "RightTracks500") {
        if (currentTrack.id < 7) {
          setCurrentTrack(RightTracks500[currentTrack.id]);
          toggle();
          toggleEnd();
        }
      } else if (currentArray == "RightTracks1000") {
        if (currentTrack.id < 7) {
          setCurrentTrack(RightTracks1000[currentTrack.id]);
          toggle();
          toggleEnd();
        }
      } else if (currentArray == "RightTracks2000") {
        if (currentTrack.id < 7) {
          setCurrentTrack(RightTracks2000[currentTrack.id]);
          toggle();
          toggleEnd();
        }
      } else if (currentArray == "RightTracks3000") {
        if (currentTrack.id < 7) {
          setCurrentTrack(RightTracks3000[currentTrack.id]);
          toggle();
          toggleEnd();
        }
      } else if (currentArray == "RightTracks4000") {
        if (currentTrack.id < 7) {
          setCurrentTrack(RightTracks4000[currentTrack.id]);
          toggle();
          toggleEnd();
        }
      } else if (currentArray == "RightTracks6000") {
        if (currentTrack.id < 7) {
          setCurrentTrack(RightTracks6000[currentTrack.id]);
          toggle();
          toggleEnd();
        }
      }
    }
    // if (currentArray == "RightTracks6000" && currentTrack.id == 7) {
    //   let prevResult = [...result.rightEar];
    //   prevResult.push(currentTrack.db);
    //   setResult({
    //     ...result,
    //     rightEar: [...prevResult],
    //   });
    //   navigate("/");
    // }
  }, [isEnd]);

  React.useEffect(() => {
    // toggle();
  }, []);

  const handleClick = () => {
    console.log("currentTrack", currentTrack);
    console.log("result", result);

    if (currentArray.includes("LeftTrack")) {
      let prevResult = [...result.leftEar];
      prevResult.push(currentTrack.db);
      setResult({
        ...result,
        leftEar: [...prevResult],
      });
    } else if (currentArray.includes("RightTrack")) {
      let prevResult = [...result.rightEar];
      prevResult.push(currentTrack.db);
      console.log(prevResult);
      setResult({
        ...result,
        rightEar: [...prevResult],
      });
    }
    const random = Math.floor(Math.random() * colorsArray.length);
    if (colorCount <= 8) {
      setButtonColor(colorsArray[colorCount + 1]);
      setColorCount(colorCount + 1);
    } else {
      setButtonColor(colorsArray[0]);
      setColorCount(0);
    }

    if (currentArray == "LeftTracks500") {
      setCurrentArray("LeftTracks1000");
      setCurrentTrack(LeftTracks1000[0]);
    } else if (currentArray == "LeftTracks1000") {
      setCurrentArray("LeftTracks2000");
      setCurrentTrack(LeftTracks2000[0]);
      if (isEnd) {
        toggle();
        toggleEnd();
      }
    } else if (currentArray == "LeftTracks2000") {
      setCurrentArray("LeftTracks3000");
      setCurrentTrack(LeftTracks3000[0]);
      if (isEnd) {
        toggle();
        toggleEnd();
      }
    } else if (currentArray == "LeftTracks3000") {
      setCurrentArray("LeftTracks4000");
      setCurrentTrack(LeftTracks4000[0]);
      if (isEnd) {
        toggle();
        toggleEnd();
      }
    } else if (currentArray == "LeftTracks4000") {
      setCurrentArray("LeftTracks6000");
      setCurrentTrack(LeftTracks6000[0]);
      if (isEnd) {
        toggle();
        toggleEnd();
      }
    } else if (currentArray == "LeftTracks6000") {
      setCurrentArray("RightTracks500");
      setCurrentTrack(RightTracks500[0]);
      if (isEnd) {
        toggle();
        toggleEnd();
      }
    } else if (currentArray == "RightTracks500") {
      setCurrentArray("RightTracks1000");
      setCurrentTrack(RightTracks1000[0]);
      if (isEnd) {
        toggle();
        toggleEnd();
      }
    } else if (currentArray == "RightTracks1000") {
      setCurrentArray("RightTracks2000");
      setCurrentTrack(RightTracks2000[0]);
      if (isEnd) {
        toggle();
        toggleEnd();
      }
    } else if (currentArray == "RightTracks2000") {
      setCurrentArray("RightTracks3000");
      setCurrentTrack(RightTracks3000[0]);
      if (isEnd) {
        toggle();
        toggleEnd();
      }
    } else if (currentArray == "RightTracks3000") {
      setCurrentArray("RightTracks4000");
      setCurrentTrack(RightTracks4000[0]);
      if (isEnd) {
        toggle();
        toggleEnd();
      }
    } else if (currentArray == "RightTracks4000") {
      setCurrentArray("RightTracks6000");
      setCurrentTrack(RightTracks6000[0]);
      if (isEnd) {
        toggle();
        toggleEnd();
      }
    } else if (currentArray == "RightTracks6000") {
      UserResponseService.submitResponse({
        responses: location?.state?.responses,
        customerId: location.state?.customerId,
        testResult: result,
        companyId: params?.id,
      }).then((res) => {
        navigate(`/${params?.id}/testGraph`);
      });
    }
  };

  return (
    <div>
      {/* <button onClick={toggle}>{playing ? "Pause" : "Play"}</button>
      {isEnd && <p>Ended</p>} */}
      {/* <Button variant="contained" onClick={handleClick}>
        Click Me
      </Button> */}
      <div className="container" style={{ display: "none" }}>
        <h1>Hello, audio player!</h1>
        <AudioPlayer
          src="https://hanzluo.s3-us-west-1.amazonaws.com/music/wuyuwuqing.mp3"
          volume={0.5}
          // Try other props!
        />
        <p>
          <a
            href="https://github.com/lhz516/react-h5-audio-player"
            target="_blank"
          >
            Read Docs on Github
          </a>
        </p>
      </div>
      <Grid
        container
        direction="column"
        justifyContent="center"
        alignItems="center"
      >
        <h4>Tap the below once you hear the tone</h4>

        <Button
          variant="container"
          style={{
            marginTop: "2rem",
            borderRadius: "50%",
            backgroundColor: buttonColor,
            color: "white",
            padding: "3rem",
          }}
          onClick={handleClick}
        >
          <CheckIcon style={{ fontSize: "5rem" }} />
        </Button>
      </Grid>
    </div>
  );
};

export default Player;

// https://github.com/lhz516/react-h5-audio-player
