"use client";
import { observer } from "mobx-react-lite";
import { useLayoutEffect, useRef, useState } from "react";
import ChoiceImage from "./ChoiceImage";
import { energyState } from "./energyState";
import styles from "./page.module.css";

function indexToColor(index: number): string {
  const red = Math.floor(255 * (index / 14));
  const blue = Math.floor(255 * ((14 - index) / 14));
  return `rgb(${red}, 0, ${blue})`;
}

const EnergyClient = observer(() => {
  const audioRef = useRef<HTMLAudioElement>(null);
  const [hasStarted, setHasStarted] = useState(false); // State to track if the user has started

  useLayoutEffect(() => {
    if (audioRef.current) {
      energyState.setAudioElement(audioRef.current);
    }
  }, [audioRef]);

  const handleStartClick = () => {
    setHasStarted(true); // Update state to indicate start
  };

  return (
    <div className={styles.energy}>
      {!hasStarted && ( // Conditionally render the overlay if the app hasn't started
        <div className={styles.overlay} onClick={handleStartClick}>
          <div className={styles.startMessage}>Click to start</div>
        </div>
      )}
      <div>
        <h1>Energy</h1>
        <audio ref={audioRef} />

        {energyState.choices.length === 0 ? (
          <button onClick={energyState.loadInitialData}>Click to begin</button>
        ) : null}

        {energyState.choices.map((choiceRow, rowIndex) => (
          <div key={rowIndex}>
            {choiceRow.map((choice, colIndex) =>
              choice.type ? (
                <div
                  key={choice.id}
                  className={`${styles.choiceHoverEffect} ${
                    energyState.selectedChoices.has(choice.id)
                      ? styles.choiceSelected
                      : ""
                  }`}
                  style={{
                    // border: energyState.selectedChoices.has(choice.id)
                    //   ? "2px solid red"
                    //   : undefined,
                    width: 80,
                    height: 80,
                    padding: 10,
                    display: "inline-block",
                    backgroundColor: indexToColor(colIndex),
                    opacity:
                      energyState.choices.length - 1 === rowIndex ? 1 : 0.5,
                  }}
                  onMouseEnter={async () => {
                    if (choice.type === "preset") {
                      const id = await energyState.getSimilarIdToPreset(choice);
                      energyState.playId(id);
                    }
                  }}
                  // onMouseLeave={() => {
                  //   energyState.pause();
                  // }}
                  onClick={() => {
                    if (choice.id === "random") {
                      energyState.loadInitialData();
                    } else {
                      energyState.getSimilar(choice, rowIndex);
                    }
                  }}
                >
                  {choice.id}
                </div>
              ) : (
                <ChoiceImage
                  key={choice.id}
                  choice={choice}
                  rowIndex={rowIndex}
                  totalRows={energyState.choices.length - 1}
                />
              )
            )}
          </div>
        ))}
      </div>
    </div>
  );
});

export default EnergyClient;
