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

const colorsArray = [
  "#6F1EBC",
  "#FBB03F",
  "#DDBAFF",
  "#252525",
  "#6C6C6C",
  "#EC2D2D",
  "#A9A9A9",
  "#71FF1B",
  "#FFF61B",
  "#FF1B1B",
];

const VoicePlayer = ({ 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 player = useRef();
  const [result, setResult] = useState({
    leftEar: [],
    rightEar: [],
  });
  const [disabledButt, setDisabledButt] = useState(false);
  const [autoSound, setAutoSound] = useState(true);
  const [company, setCompany] = React.useState(location?.state?.company);

  const audiofunction = () => {
    // player.current.audio.current.play();
  };

  React.useEffect(() => {
    setTimeout(audiofunction, 5000);
    // audiofunction();
  }, []);
  // const [currentSong, setCurrentSong] = useState(0);
  // const [song, setSong] = useState(RightTracks500[0]);
  // React.useEffect(() => {
  //   console.log("Inside useeffect currentSong")
  //   setSong(RightTracks500[currentSong]);
  // }, [currentSong]);
  // const song = RightTracks500[currentSong];

  console.log(currentTrack);

  if (!currentTrack) return null; // don't render the player when no song is available
  const handleEnd2 = () => {
    // setCurrentSong((i) => i + 1);
  };
  const handleEnd = () => {
    if (currentArray == "RightTracks500") {
      if (currentTrack.id < 7) {
        setCurrentTrack(RightTracks500[currentTrack.id]);
      }
    } else if (currentArray == "RightTracks1000") {
      if (currentTrack.id < 7) {
        setCurrentTrack(RightTracks1000[currentTrack.id]);
      }
    } else if (currentArray == "RightTracks2000") {
      if (currentTrack.id < 7) {
        setCurrentTrack(RightTracks2000[currentTrack.id]);
      }
    } else if (currentArray == "RightTracks3000") {
      if (currentTrack.id < 7) {
        setCurrentTrack(RightTracks3000[currentTrack.id]);
      }
    } else if (currentArray == "RightTracks4000") {
      if (currentTrack.id < 7) {
        setCurrentTrack(RightTracks4000[currentTrack.id]);
      }
    } else if (currentArray == "RightTracks6000") {
      if (currentTrack.id < 7) {
        setCurrentTrack(RightTracks6000[currentTrack.id]);
      }
    }
  };

  const handleClick = () => {
    console.log("currentTrack", currentTrack);
    console.log("result", result);
    let prevResult = [];
    let updatedResult = {};
    if (currentArray.includes("LeftTrack")) {
      prevResult = [...result.leftEar];
      prevResult.push(currentTrack.db);
      updatedResult = {
        ...result,
        leftEar: [...prevResult],
      };
      setResult(updatedResult);
    } else if (currentArray.includes("RightTrack")) {
      prevResult = [...result.rightEar];
      prevResult.push(currentTrack.db);
      console.log(prevResult);
      updatedResult = {
        ...result,
        rightEar: [...prevResult],
      };
      setResult(updatedResult);
    }
    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 == "RightTracks500") {
      setCurrentArray("RightTracks1000");
      setCurrentTrack(RightTracks1000[0]);
    } else if (currentArray == "RightTracks1000") {
      setCurrentArray("RightTracks2000");
      setCurrentTrack(RightTracks2000[0]);
    } else if (currentArray == "RightTracks2000") {
      setCurrentArray("RightTracks3000");
      setCurrentTrack(RightTracks3000[0]);
    } else if (currentArray == "RightTracks3000") {
      setCurrentArray("RightTracks4000");
      setCurrentTrack(RightTracks4000[0]);
    } else if (currentArray == "RightTracks4000") {
      setCurrentArray("RightTracks6000");
      setCurrentTrack(RightTracks6000[0]);
    } else if (currentArray == "RightTracks6000") {
      setDisabledButt(true);
      setAutoSound(false);
      // UserResponseService.submitResponse({
      //   responses: location?.state?.responses,
      //   customerId: location.state?.customerId,
      //   testResult: updatedResult,
      //   companyId: params?.id,
      // }).then((res) => {
      navigate(`/${params?.id}/testGraph`, {
        state: {
          result: updatedResult,
          testType: location?.state?.testType,
          company,
          finalData: {
            responses: location?.state?.responses,
            customerId: location.state?.customerId,
            testResult: updatedResult,
            companyId: params?.id,
          },
        },
      });
      // });
    }
  };
  return (
    <div>
      {/* <button onClick={toggle}>{playing ? "Pause" : "Play"}</button>
      {isEnd && <p>Ended</p>} */}
      {/* <Button variant="contained" onClick={handleClick}>
        Click Me
      </Button> */}
      <Grid
        container
        direction="column"
        justifyContent="center"
        alignItems="center"
        // spacing={2}
      >
        <Avatar
          src={company?.logo}
          alt={company?.name}
          style={{ marginBottom: "1rem", width: 100, height: 100 }}
        />
      </Grid>
      <div className="container" style={{ display: "none" }}>
        <h1>Hello, audio player!</h1>
        <AudioPlayer
          controls={true}
          autoPlay={autoSound}
          src={currentTrack.url}
          showJumpControls={false}
          customVolumeControls={[]}
          customAdditionalControls={[]}
          onPlay={() => console.log("playing")}
          onEnded={() => handleEnd()}
          ref={player}
        />
      </div>
      <Grid
        container
        direction="column"
        justifyContent="center"
        alignItems="center"
      >
        <h4>Tap the button below once you hear the tone</h4>

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

export default VoicePlayer;

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