import React, { useState, useEffect, useRef } from "react";
import PianoKeyboard from "./PianoKeyboard";
import MidNoteDataReceiver from "../DataRecievers/MidiNoteDataReceiver.js";
import CenterGrowSlider from "./CenterGrowSlider.js";
// import { Slider } from "@mui/material";
// import { styled } from "@mui/material/styles";

// eslint-disable-next-line react/prop-types

export default function MidiNoteInfo() {
  const [notes, setNotes] = useState([]);
  const [inputCents, setInputCents] = useState(0);
  const [outputCents, setOutputCents] = useState(0);
  const [autotuneNote, setAutotuneNote] = useState(0);
  const dataReceiverRef = useRef(null);
  const isActiveRef = useRef(true);

  function getCharfromNoteIndex(index) {
    const NOTE_NAMES = [
      "C",
      "C♯",
      "D",
      "D♯",
      "E",
      "F",
      "F♯",
      "G",
      "G♯",
      "A",
      "A♯",
      "B",
    ];
    if (typeof index !== "number" || isNaN(index)) return "";
    return NOTE_NAMES[index % NOTE_NAMES.length];
  }

  useEffect(() => {
    dataReceiverRef.current = new MidNoteDataReceiver();
    isActiveRef.current = true;

    function render() {
      if (!isActiveRef.current) return;
      if (dataReceiverRef.current) {
        setNotes(dataReceiverRef.current.getNotes());
        setInputCents(dataReceiverRef.current.getInputCents());
        setOutputCents(dataReceiverRef.current.getOutputCents());
        setAutotuneNote(dataReceiverRef.current.getAutotuneNote());
      }
      window.requestAnimationFrame(render);
    }

    window.requestAnimationFrame(render);
    return function cleanup() {
      isActiveRef.current = false;
      if (dataReceiverRef.current) dataReceiverRef.current.unregister();
    };
  }, []);

  return (
    <div style={{ padding: "1rem" }}>
      <PianoKeyboard heldNotes={notes} />
      <h1>Autotune Note: {getCharfromNoteIndex(autotuneNote)}</h1>
      <label>Input cents</label>
      <CenterGrowSlider value={inputCents} />
      <label>Output cents</label>
      <CenterGrowSlider value={outputCents} />
    </div>
  );
}
