import React, { useState, useContext, useEffect } from "react";
import { showToast, GlobalContext } from "Src/globalContext";
import { updateLyricsPublicAPI } from "Src/services/workOrderService";
import { replaceNextLineToBrTag, replaceBrTagToNextLine } from "Utils/utils";
import { useLocation } from "react-router-dom";
import { components } from "react-select";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";

const WorkOrderLyrics = ({ lyrics, subProjectId, setLyrics }) => {
  const { dispatch: globalDispatch, state } = useContext(GlobalContext);
  const location = useLocation();
  const { subProjectLyricsEditWorkOrder } = state;
  const [lyricsVal, setLyricsVal] = 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 = async (e) => {
    e.preventDefault();
    const lyricsIndex = subProjectLyricsEditWorkOrder.findIndex(
      (lyric) => lyric.subproject_id === subProjectId
    );

    if (lyricsIndex > -1) {
      const updatedLyrics = [...subProjectLyricsEditWorkOrder];
      updatedLyrics[lyricsIndex] = {
        ...updatedLyrics[lyricsIndex],
        lyrics: e.target.value,
        subproject_id: subProjectId,
      };

      globalDispatch({
        type: "SET_SUB_PROJECT_LYRICS_EDIT_WORK_ORDER",
        payload: updatedLyrics,
      });
    } else {
      globalDispatch({
        type: "SET_SUB_PROJECT_LYRICS_EDIT_WORK_ORDER",
        payload: [
          ...subProjectLyricsEditWorkOrder,
          {
            subproject_id: subProjectId,
            lyrics: e.target.value,
          },
        ],
      });

      await updateLyricsPublicAPI({
        subproject_id: subProjectId,
        lyrics: e.target.value,
      });
    }
  };

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

  return (
    <div className="flex flex-col">
      {/* Header */}
      <div className="mb-4 flex items-center justify-between">
        <div className="flex items-center gap-2">
          <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>

        {!isEngineerView && (
          <button
            className="inline-flex items-center justify-center rounded-md bg-primary px-4 py-2 text-sm font-medium text-white 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="rounded border border-strokedark bg-boxdark p-4">
        <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>

      {/* Helper Text */}
      {isEngineerView && (
        <div className="mt-2 flex items-center gap-2 text-xs text-bodydark2">
          <FontAwesomeIcon icon="fa-solid fa-circle-info" />
          <span>Engineer can't edit Lyrics</span>
        </div>
      )}
    </div>
  );
};

export default WorkOrderLyrics;
