import React, { useEffect } from "react";
import { showToast, GlobalContext } from "Src/globalContext";
import { replaceNextLineToBrTag, replaceBrTagToNextLine } from "Utils/utils";

const Lyrics = ({ canUpload = true, subProjectId, lyrics, setLyrics }) => {
  const { dispatch: globalDispatch, state } = React.useContext(GlobalContext);

  const { subProjectLyrics } = state;

  const [lyricsVal, setLyricsVal] = React.useState(
    lyrics ? replaceBrTagToNextLine(lyrics) : ""
  );
  console.log(subProjectLyrics, lyrics);

  useEffect(() => {
    setLyricsVal(lyrics ? replaceBrTagToNextLine(lyrics) : "");
  }, [lyrics]);

  const submitLyrics = (e) => {
    e.preventDefault();
    if (lyricsVal === "" || !lyricsVal) {
      showToast(globalDispatch, "Lyrics cannot be empty.", 5000, "error");
      return;
    }
    setLyrics(replaceNextLineToBrTag(lyricsVal));
  };

  const handleOnChangeLyrics = (e) => {
    e.preventDefault();

    const lyricsIndex = subProjectLyrics.findIndex(
      (lyric) => lyric.subproject_id === subProjectId
    );

    if (lyricsIndex > -1) {
      const updatedLyrics = [...subProjectLyrics];
      updatedLyrics[lyricsIndex].lyrics = e.target.value;
      globalDispatch({
        type: "SET_SUB_PROJECT_LYRICS",
        payload: updatedLyrics,
      });
    } else {
      globalDispatch({
        type: "SET_SUB_PROJECT_LYRICS",
        payload: [
          ...subProjectLyrics,
          {
            subproject_id: subProjectId,
            lyrics: e.target.value,
          },
        ],
      });
    }
  };

  return (
    <div className="mt-4 flex w-full flex-col flex-wrap justify-between">
      <h4 className="text-md mb-2 items-center font-semibold text-white">
        Lyrics
      </h4>
      <textarea
        className="h-24 w-full rounded-md border border-gray-500 bg-gray-700 p-2 text-white shadow placeholder:text-gray-200"
        placeholder="Write lyrics here..."
        value={lyricsVal}
        onChange={(e) => {
          setLyricsVal(e.target.value);
          handleOnChangeLyrics(e);
        }}
      ></textarea>
      {canUpload && (
        <button
          className="mt-2 w-16 rounded bg-green-700 px-2 py-1 font-bold text-white hover:bg-green-600"
          onClick={(e) => submitLyrics(e)}
        >
          Save
        </button>
      )}
    </div>
  );
};

export default Lyrics;
