import React, { useEffect } from "react";
import { showToast, GlobalContext } from "Src/globalContext";
import { replaceNextLineToBrTag, replaceBrTagToNextLine } from "Utils/utils";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { useLocation } from "react-router-dom";

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

  const [lyricsVal, setLyricsVal] = React.useState(
    lyrics ? replaceBrTagToNextLine(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,
      });
      setLyricsVal(updatedLyrics[lyricsIndex].lyrics);
    } else {
      globalDispatch({
        type: "SET_SUB_PROJECT_LYRICS",
        payload: [
          ...subProjectLyrics,
          {
            subproject_id: subProjectId,
            lyrics: e.target.value,
          },
        ],
      });
      setLyricsVal(e.target.value);
    }
  };

  const isEngineerView = location.pathname.includes("/work-order/engineer");

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

    if (lyricsIndex > -1) {
      const updatedLyrics = [...subProjectLyrics];
      setLyricsVal(updatedLyrics[lyricsIndex].lyrics);
    }
  }, [subProjectLyrics]);

  return (
    <div className="flex flex-col">
      {/* Header */}
      <div className="flex justify-between items-center mb-4">
        <div className="flex gap-2 items-center">
          <FontAwesomeIcon
            icon="fa-solid fa-pen-to-square"
            className="text-lg text-primary"
          />
          <h3 className="text-lg font-semibold text-white">Song Lyrics</h3>
        </div>

        {canUpload && !isEngineerView && (
          <button
            className="inline-flex justify-center items-center px-4 py-2 text-sm font-medium text-white rounded-md bg-primary hover:bg-opacity-90 disabled:bg-opacity-50"
            onClick={submitLyrics}
            disabled={!lyricsVal}
          >
            <FontAwesomeIcon icon="fa-solid fa-save" className="mr-2" />
            Save
          </button>
        )}
      </div>

      {/* Lyrics Editor */}
      <div className="p-4 rounded border border-strokedark bg-boxdark">
        <textarea
          className="min-h-[200px] w-full resize-y rounded border border-form-strokedark bg-form-input px-4 py-3 text-white placeholder:text-bodydark2 focus:border-primary focus:outline-none"
          placeholder={
            isEngineerView
              ? "No lyrics have been added yet."
              : "Write your song lyrics here..."
          }
          value={lyricsVal}
          onChange={(e) => {
            setLyricsVal(e.target.value);
            handleOnChangeLyrics(e);
          }}
          readOnly={isEngineerView}
        />
      </div>
    </div>
  );
};

export default Lyrics;
