import React, { useContext, useEffect, useState } from "react";
import AudioFileIcon from "@/assets/svgs/AudioFileIcon";
import { FaCaretDown, FaCodeMerge } from "react-icons/fa6";
import { GlobalContext, showToast } from "@/context/Global";
import { InteractiveButton } from "@/components/InteractiveButton";
import MkdSDK from "@/utils/MkdSDK";
import { generateUUID } from "@/utils/utils";
import { TbReplace } from "react-icons/tb";
import Modal from "react-modal";
import { FaMicrophoneAlt, FaSpinner, FaSquare } from "react-icons/fa";
import { CgSpinner } from "react-icons/cg";
import "regenerator-runtime/runtime";
import SpeechRecognition, {
  useSpeechRecognition,
} from "react-speech-recognition";

const customStyles = {
  content: {
    top: "50%",
    left: "50%",
    right: "auto",
    bottom: "auto",
    marginRight: "-50%",
    transform: "translate(-50%, -50%)",
  },
};

const sdk = new MkdSDK();

const Transcribe = ({
  transcripts,
  audioDesc,
  saveData,
  isFullView,
  isRecording,
  setIsRecording,
  audioPlayerRef,
  mediaRecorderRef,
  audioChunksRef,
  hasRecordedAudioFile,
  setHasRecordedAudioFile,
  transcribeLoading,
  setTranscribeLoading,
  transcribeResult,
  setTranscribeResult,
  audioFile,
  setAudioFile,
  setIsFullView,
  transcribeBy,
  setTranscribeBy,
  isCreateSection,
  setIsCreateSection,
  sections,
  setSections,
  handleSaveTranscribe,
  resultTextarea,
  setResultTextarea,
  selectedSection,
  setSelectedSection,
  activePdfPage,
  setIsSpeechToText,
  saveTranscribeLoading,
  setSaveTranscribeLoading,
  setIsBlocking,
  isSaved
}) => {
  const [hasSelectedAudioFile, setHasSelectedAudioFile] = useState(false);
  const [isLangEnglish, setIsLangEnglish] = useState(true);
  const { dispatch: globalDispatch } = useContext(GlobalContext);
  const [sectionName, setSectionName] = useState("");
  const [sectionDescription, setSectionDescription] = useState("");
  const [isApending, setIsApending] = useState(true);
  const [isReplacing, setIsReplacing] = useState(true);
  const [transcribeType, setTranscribeType] = useState("append");
  const [description, setDescription] = useState("");
  const [transcribeTextBy, setTranscribeTextBy] = useState("default");
  const [isListening, setIsListening] = useState(false);
  const [transcriptLoading, setTranscriptLoading] = useState(false);
  const { transcript, browserSupportsSpeechRecognition, resetTranscript } =
    useSpeechRecognition();
  let subtitle;

  async function handleFileInput(el) {
    const fileObj = el.target.files[0];
    if (fileObj) {
      const objectURL = URL.createObjectURL(fileObj);
      audioPlayerRef.current.src = objectURL;
      setHasSelectedAudioFile(true);
      setAudioFile(fileObj);
    }
  }

  async function handleTranscribeBtn(type) {
    try {
      if (audioFile) {
        setTranscribeLoading(true);
        const result = isLangEnglish
          ? await transcribeAudio(audioFile)
          : await translateAudio(audioFile);
        setTranscribeResult(result?.message);
        type === "replace"
          ? setResultTextarea(() => result?.message)
          : setResultTextarea((prev) =>
              prev?.length ? `${prev}\n${result?.message}` : result?.message
            );
        setTranscribeTextBy("default");
        setIsBlocking(resultTextarea?.length > 0 ?  true : false);
      }
    } catch (error) {
      showToast(globalDispatch, error, 1500, "error");
    } finally {
      setHasRecordedAudioFile(false);
      setHasSelectedAudioFile(false);
      setTranscribeLoading(false);
    }
  }

  async function transcribeAudio(audioFile) {
    try {
      let formData = new FormData();
      formData.append("file", audioFile);
      const transcriptRes = await sdk.gptTranscribe(formData);
      return transcriptRes;
    } catch (error) {
      console.error(error);
    }
  }

  async function translateAudio(audioFile) {
    let transcriptRes;
    try {
      let formData = new FormData();
      formData.append("file", audioFile);
      transcriptRes = await sdk.gptTranslate(formData);
      return transcriptRes;
    } catch (error) {
      console.error(error);
    }
    return transcriptRes;
  }

  function copyToClipboard(text) {
    navigator.clipboard.writeText(text);
    showToast(globalDispatch, "Copied to clipboard");
  }

  const startRecording = async () => {
    setIsRecording(true);
    setTranscribeTextBy("audio");
    mediaRecorderRef.current = null;
    audioChunksRef.current = [];
    setAudioFile(null);
    try {
      const stream = await navigator.mediaDevices.getUserMedia({ audio: true });

      mediaRecorderRef.current = new MediaRecorder(stream);

      mediaRecorderRef.current.ondataavailable = (event) => {
        if (event.data.size > 0) {
          audioChunksRef.current.push(event.data);
        }
      };

      mediaRecorderRef.current.onstop = () => {
        const audioBlob = new Blob(audioChunksRef.current, {
          type: "audio/wav",
        });
        const maxSizeBytes = 23 * 1024 * 1024; // 23 MB in bytes
        if (audioBlob.size > maxSizeBytes) {
          alert(
            "Recording size exceeds the limit (23 MB). Please record a shorter audio."
          );
          // You may want to handle this case differently, e.g., clear recording and prevent further actions
          return;
        }

        const audioUrl = URL.createObjectURL(audioBlob);
        audioPlayerRef.current.src = audioUrl;
        const audioFile = new File([audioBlob], "recorded_audio.wav", {
          type: "audio/wav",
        });
        setAudioFile(audioFile);
        setHasRecordedAudioFile(true);
        setIsApending(true);
        setIsReplacing(true);
      };

      mediaRecorderRef.current.start();
    } catch (error) {
      setIsRecording(false);
      console.error("Error accessing microphone:", error);
      showToast(globalDispatch, "Error accessing microphone", 1500, "error");
    }
  };

  const stopRecording = async () => {
    if (mediaRecorderRef.current) {
      mediaRecorderRef.current.stop();
      const tracks = mediaRecorderRef.current.stream.getTracks();
      tracks.forEach((track) => track.stop());
      mediaRecorderRef.current = null;
      audioChunksRef.current = [];
      await handleTranscribeBtn(audioFile);
      setAudioFile("");
      setIsRecording(false);
    }
  };

  useEffect(() => {
    audioPlayerRef.current.src = audioDesc?.content;

    setResultTextarea(transcripts?.transcript || "");
    setSaveTranscribeLoading(false);
    const section_desc = sections?.find(
      (item) => item?.id === selectedSection
    )?.description;
    setDescription(section_desc || "");
  }, [transcripts, audioDesc, selectedSection]);

  useEffect(() => {
    if (audioPlayerRef.current) {
      audioPlayerRef.current.load();
      // audioPlayerRef.current.play();
    }
  }, [audioPlayerRef?.current?.src]);

  useEffect(() => {
    audioPlayerRef.current.src = audioDesc?.content;
    setResultTextarea(transcripts?.transcript || "");
    setTranscribeTextBy("default");
  }, [transcribeBy === "page" ? activePdfPage : selectedSection]);

  useEffect(() => {
    const transcript = !transcripts?.transcript ? "" : transcripts?.transcript;
    if (transcript !== resultTextarea) {
      setIsBlocking(resultTextarea?.length > 0 ?  true : false);
    } else {
      setIsBlocking(false);
    }
  }, [resultTextarea]);

  const handleSaveSection = () => {
    if (!sectionName?.length) {
      return showToast(globalDispatch, "Section Name missing", 2000, "error");
    }

    const isExist = sections?.some(
      (item) => item?.name?.toLowerCase() === sectionName?.toLowerCase()
    );
    if (!isExist) {
      const newsection = {
        id: generateUUID(),
        name: sectionName,
        description: sectionDescription,
      };
      setSections([...sections, newsection]);
      saveData("sections", [...sections, newsection]);
      setSelectedSection(newsection?.id);
    } else {
      showToast(globalDispatch, "Section Already Exist!", 2000, "error");
    }

    setSectionName("");
    setSectionDescription("");
    closeModal();
  };

  const openModal = () => {
    setIsCreateSection(true);
  };

  const handleEditDescription = () => {
    if (selectedSection?.length) {
      const selectedIndex = sections.findIndex((section) => {
        return section && section.id === selectedSection;
      });

      const existArr = sections;
      existArr[selectedIndex].description = description;
      setSections([...existArr]);
      saveData("sections", existArr);
    }
  };

  const closeModal = () => {
    setIsCreateSection(false);
    setSectionName("");
    setSectionDescription("");
  };

  if (!browserSupportsSpeechRecognition) {
    return <span>Browser doesn't support speech recognition.</span>;
  }

  const handleSpeechToText = () => {
    setTranscriptLoading(true);
    if (!isListening) {
      resetTranscript();
      SpeechRecognition.startListening({ continuous: true, language: "en-IN" });
      setIsListening(true);
      setTranscribeTextBy("speech");
      setIsSpeechToText(true);
      setTimeout(() => {
        setTranscriptLoading(false);
      }, 1000);
    } else {
      setTimeout(() => {
        SpeechRecognition.stopListening();
        setIsListening(false);
        setTranscribeTextBy("default");
        setIsSpeechToText(false);
        setTranscriptLoading(false);
        setResultTextarea((prev) =>
          prev?.length ? `${prev} \n\n${transcript}` : transcript
        );
      }, 1000);
    }
  };

  return (
    <>
      {isFullView ? (
        <div className="h-[30vh]">
          <div className="fixed bottom-0 left-0 right-0 min-w-[95vw] h-[28vh]">
            <div className="flex items-end justify-between px-5">
              <div>
                <div className="flex w-[13rem] flex-col">
                  <label
                    htmlFor="transcript_by"
                    className="text-sm text-gray-700"
                  >
                    Transcript By
                  </label>
                  <select
                    id="transcript_by"
                    value={transcribeBy}
                    onChange={(event) => {
                      setTranscribeBy(event.target.value);
                      setSelectedSection("");
                    }}
                    className="rounded-md border border-[#C6C6C6] shadow-sm hover:bg-[#f4f4f4]"
                  >
                    <option value="" disabled>
                      Transcript By
                    </option>
                    <option value="page">Page</option>
                    <option value="section">Section</option>
                  </select>
                </div>
                {transcribeBy === "section" ? (
                  <div className="flex-end mt-3 flex flex-col justify-start gap-3">
                    <div className="flex w-[13rem] flex-col">
                      <label
                        htmlFor="sections"
                        className="text-sm text-gray-700"
                      >
                        Sections
                      </label>
                      <select
                        id="sections"
                        value={selectedSection}
                        onChange={(event) =>
                          setSelectedSection(event.target.value)
                        }
                        className="rounded-md border border-[#C6C6C6] shadow-sm hover:bg-[#f4f4f4]"
                      >
                        <option value="" disabled>
                          {sections?.length > 0
                            ? "Select Section"
                            : "No Sections Added"}
                        </option>
                        {sections?.map((section) => (
                          <option key={section.id} value={section?.id}>
                            {section?.name}
                          </option>
                        ))}
                      </select>
                    </div>
                  </div>
                ) : null}
                <div>
                  {selectedSection?.length ? (
                    <div className="mt-3 flex flex-1 flex-col">
                      <label
                        htmlFor="transcript_by"
                        className="text-sm text-gray-700"
                      >
                        Description
                      </label>
                      <textarea
                        className="text-medium flex min-h-[120px] !w-[15vw] max-w-[100vw] flex-1 resize-none rounded-lg border border-[#a8a8a8] px-3 py-1.5 text-[#525252]"
                        name="description"
                        value={description}
                        onChange={(event) => setDescription(event.target.value)}
                      />
                      {sections?.find(
                        (section) => section?.id === selectedSection
                      )?.description !== description ? (
                        <div className="mt-3">
                          <button
                            onClick={handleEditDescription}
                            className=" rounded-md bg-[#4F46E5] px-6 py-1.5 text-center text-white shadow-sm"
                          >
                            Save Edits
                          </button>
                        </div>
                      ) : (
                        <></>
                      )}
                    </div>
                  ) : (
                    <></>
                  )}
                </div>
              </div>
              <div className="mt-5 flex flex-col items-center gap-3">
                <button
                  onClick={() => setIsFullView(false)}
                  className="w-full rounded-md bg-red-500  px-3 py-2 text-center text-white shadow-sm"
                >
                  Exit Full View
                </button>
                <button
                  onClick={handleSaveTranscribe}
                  className="w-[12rem] rounded-md bg-[#4F46E5] px-3 py-2 text-center text-white shadow-sm"
                >
                  {saveTranscribeLoading ? (
                    <span className="flex items-center justify-center gap-2">
                      <CgSpinner className="text-[1.2rem] text-white motion-safe:animate-spin" />
                      Saving...
                    </span>
                  ) : (
                    "Save Transcription"
                  )}
                </button>
                {isSaved && <span className="text-green-500">Saved!</span>}
              </div>
            </div>
            <div className="flex min-w-[90vw] gap-6 px-5">
              <div
                className={`${
                  transcribeTextBy === "default" || transcribeTextBy === "audio"
                    ? "block"
                    : "hidden"
                }`}
              >
                <div className="hidden">
                  <audio
                    onClick={() => audioPlayerRef.current.play()}
                    className={`${isRecording ? "hidden" : "block"}`}
                    controls
                    ref={audioPlayerRef}
                  ></audio>
                </div>
                <div className="mt-5 flex flex-col items-stretch gap-1">
                  <div
                    className={`min-w-24 relative flex max-w-fit flex-col items-center justify-center rounded-lg border border-[#a8a8a8] bg-[#f4f4f4] p-5`}
                  >
                    <AudioFileIcon className="mb-1" />
                    {!isRecording && (
                      <button
                        className="absolute left-0 h-full w-full opacity-0"
                        onClick={startRecording}
                        disabled={isRecording}
                      ></button>
                    )}

                    <p className="text-medium gap-3 text-xs capitalize text-[#525252]">
                      <span>
                        {isRecording ? "Recording..." : "Record an audio"}
                      </span>
                      {isRecording && (
                        <button
                          className="ml-3 h-4 w-4 bg-red-500"
                          onClick={stopRecording}
                          disabled={!isRecording}
                        ></button>
                      )}
                    </p>
                  </div>
                  <div>
                    {resultTextarea?.length > 0 ? (
                      <div
                        className={`mt-1 flex items-center rounded-md border border-[#E0E0E0] bg-[#4F46E5] pr-1.5 text-white shadow-sm ${
                          hasRecordedAudioFile ? "flex" : "hidden"
                        }`}
                      >
                        <button
                          onClick={() => handleTranscribeBtn(transcribeType)}
                          className="disabled={transcribeLoading} px-3 text-sm"
                        >
                          {transcribeLoading ? (
                            <span className="my-1.5 flex items-center justify-center gap-1">
                              <CgSpinner className="text-[1.2rem] text-white motion-safe:animate-spin" />
                              Transcribing
                            </span>
                          ) : (
                            "Transcribe"
                          )}
                        </button>

                        {!transcribeLoading && (
                          <div className="relative">
                            <button title="Profile" className="peer">
                              <div className="flex items-center gap-3 border-l-2 border-gray-800 py-2 pl-2 pr-1">
                                <FaCaretDown />
                              </div>
                            </button>
                            <ul className="absolute right-0 top-[100%] z-20 ml-4 mr-[-9px] hidden rounded-md border border-[#a8a8a8] bg-white text-sm text-[#525252] shadow-md hover:block focus:block peer-focus:block peer-focus-visible:block">
                              <li>
                                <button
                                  onClick={() => setTranscribeType("append")}
                                  className={` flex w-full items-center justify-center gap-2 px-7 py-1 text-sm font-medium
                                ${
                                  transcribeType === "append"
                                    ? " !bg-gray-300  !text-[#130b0b]"
                                    : "!text-[#130b0b]"
                                }
                              `}
                                >
                                  <FaCodeMerge />
                                  <span>Append</span>
                                </button>
                              </li>
                              <li>
                                <button
                                  onClick={() => setTranscribeType("replace")}
                                  className={` flex w-full items-center justify-center gap-2 px-7 py-1 text-sm
                                ${
                                  transcribeType === "replace"
                                    ? " !bg-gray-300  !text-[#130b0b]"
                                    : "!text-[#130b0b]"
                                }
                              `}
                                >
                                  <TbReplace />
                                  <span>Replace</span>
                                </button>
                              </li>
                            </ul>
                          </div>
                        )}
                      </div>
                    ) : (
                      <InteractiveButton
                        className={` mt-3 flex min-w-[150px] max-w-fit items-center justify-center self-end rounded-md bg-[#4F46E5] ${
                          transcribeLoading ? "!px-2.5" : "!px-[1.95rem]"
                        } !py-2 !leading-5 text-white shadow-sm disabled:cursor-not-allowed ${
                          hasRecordedAudioFile && isApending ? "flex" : "hidden"
                        }`}
                        loading={transcribeLoading}
                        disabled={transcribeLoading}
                        onClick={() => {
                          handleTranscribeBtn(transcribeType);
                          setIsReplacing(false);
                        }}
                      >
                        {transcribeLoading ? "Transcribing" : "Transcribe"}
                      </InteractiveButton>
                    )}
                  </div>
                </div>
              </div>
              <div className="flex-1">
                <textarea
                  value={resultTextarea}
                  onChange={(e) => setResultTextarea(e.target.value)}
                  className="text-medium relative !z-20 my-5 h-[14vh]  w-full rounded-lg border border-[#a8a8a8] bg-[#f4f4f4] p-5 text-[#525252]"
                ></textarea>
              </div>
              <div
                className={`${
                  transcribeTextBy === "default" ||
                  transcribeTextBy === "speech"
                    ? "block"
                    : "hidden"
                }`}
              >
                <button
                  className=" min-w-36 mt-5 flex w-full max-w-fit flex-col items-center justify-center rounded-lg border border-[#a8a8a8] bg-[#f4f4f4] p-5"
                  onClick={handleSpeechToText}
                  disabled={isRecording}
                >
                  {" "}
                  <FaMicrophoneAlt className="mb-2 text-[1.5rem] text-[#4f46e5]" />
                  <p className="text-medium gap-3 text-xs capitalize text-[#525252]">
                    {transcriptLoading ? (
                      <div className="flex items-center gap-1">
                        <FaSpinner className="animate-spin text-[1.2rem] text-[#4f46e5]" />
                        <span>Loading...</span>
                      </div>
                    ) : isListening ? (
                      <div className="flex items-center gap-1">
                        <span>Listening..</span>
                        <FaSquare className="animate-pulse text-[1.2rem] text-red-500" />
                      </div>
                    ) : (
                      "Speech To Text"
                    )}
                  </p>
                </button>
              </div>
            </div>
          </div>
        </div>
      ) : (
        <div className="mt-[-14px]">
          <div>
            <div className="flex items-start gap-4">
              <div>
                <div className="flex w-[16rem] flex-col">
                  <label
                    htmlFor="transcript_by"
                    className="text-sm text-gray-700"
                  >
                    Transcript By
                  </label>
                  <select
                    id="transcript_by"
                    value={transcribeBy}
                    onChange={(event) => {
                      setTranscribeBy(event.target.value);
                      setSelectedSection("");
                    }}
                    className="mb-3 rounded-md border border-[#C6C6C6] shadow-sm hover:bg-[#f4f4f4]"
                  >
                    <option value="" disabled>
                      Transcript By
                    </option>
                    <option value="page">Page</option>
                    <option value="section">Section</option>
                  </select>
                </div>
                {transcribeBy === "section" ? (
                  <div className="flex-end flex justify-start gap-3">
                    <div className="flex w-[16rem] flex-col">
                      <label
                        htmlFor="sections"
                        className="text-sm text-gray-700"
                      >
                        Sections
                      </label>
                      <select
                        id="sections"
                        value={selectedSection}
                        onChange={(event) =>
                          setSelectedSection(event.target.value)
                        }
                        className="rounded-md border border-[#C6C6C6] shadow-sm hover:bg-[#f4f4f4]"
                      >
                        <option value="" disabled>
                          {sections?.length > 0
                            ? "Select Section"
                            : "No Sections Added"}
                        </option>
                        {sections?.map((section) => (
                          <option value={section?.id}>{section?.name}</option>
                        ))}
                      </select>
                    </div>
                    <div className="mt-5">
                      <button
                        onClick={openModal}
                        className="mb-0 w-full rounded-md bg-[#4F46E5] px-5 py-[0.6rem] text-center text-white shadow-sm"
                      >
                        Add&nbsp;
                      </button>
                    </div>
                  </div>
                ) : null}
              </div>
            </div>
          </div>
          <div>
            <div>
              {selectedSection?.length ? (
                <div className="mt-3 flex flex-1 flex-col">
                  <label
                    htmlFor="transcript_by"
                    className="text-sm text-gray-700"
                  >
                    Description
                  </label>
                  <textarea
                    className="text-medium flex min-h-[150px] !w-full max-w-[100vw] flex-1 resize-none rounded-lg border border-[#a8a8a8] px-3 py-1.5 text-[#525252]"
                    name="description"
                    value={description}
                    onChange={(event) => setDescription(event.target.value)}
                  />
                  {sections?.find((section) => section?.id === selectedSection)
                    ?.description !== description ? (
                    <div className="mt-3">
                      <button
                        onClick={handleEditDescription}
                        className=" rounded-md bg-[#4F46E5] px-6 py-1.5 text-center text-white shadow-sm"
                      >
                        Save Edits
                      </button>
                    </div>
                  ) : (
                    <></>
                  )}
                </div>
              ) : (
                <></>
              )}
            </div>
            <div
              className={`flex items-end ${
                isRecording ? "justify-end" : "justify-between"
              } pt-3`}
            >
              <div>
                <div
                  className={`${
                    transcribeTextBy === "default" ||
                    transcribeTextBy === "speech"
                      ? "block"
                      : "hidden"
                  }`}
                >
                  <button
                    className=" min-w-36 flex h-full w-full max-w-fit flex-col items-center justify-center rounded-lg border border-[#a8a8a8] bg-[#f4f4f4] p-5"
                    onClick={handleSpeechToText}
                    disabled={isRecording}
                  >
                    {" "}
                    <FaMicrophoneAlt className="mb-3 text-[1.5rem] text-[#4f46e5]" />
                    <p className="text-medium gap-3 text-xs capitalize text-[#525252]">
                      <p className="text-medium gap-3 text-xs capitalize text-[#525252]">
                        {transcriptLoading ? (
                          <div className="flex items-center gap-1">
                            <FaSpinner className="animate-spin text-[1.2rem] text-[#4f46e5]" />
                            <span>Loading...</span>
                          </div>
                        ) : isListening ? (
                          <div className="flex items-center gap-1">
                            <span>Listening..</span>
                            <FaSquare className="animate-pulse text-[1.2rem] text-red-500" />
                          </div>
                        ) : (
                          "Speech To Text"
                        )}
                      </p>
                    </p>
                  </button>
                </div>
                <div
                  className={` ${
                    transcribeTextBy === "audio" && !isRecording
                      ? "block"
                      : "hidden"
                  } mt-5`}
                >
                  <p>Your Audio File</p>
                  <audio
                    className="max-w-md rounded-lg border border-[#a8a8a8] bg-[#f4f4f4] px-4 shadow-sm"
                    onClick={() => audioPlayerRef.current.play()}
                    controls
                    ref={audioPlayerRef}
                  />
                </div>
              </div>

              <div
                className={`${
                  transcribeTextBy === "default" || transcribeTextBy === "audio"
                    ? "flex"
                    : "hidden"
                } !min-w-[8rem] max-w-fit flex-col items-end  justify-end`}
              >
                <div
                  className={`min-w-36 relative flex max-w-fit flex-col items-center justify-center rounded-lg border border-[#a8a8a8] bg-[#f4f4f4] p-5`}
                >
                  <AudioFileIcon className="mb-2" />
                  {!isRecording && (
                    <button
                      className="absolute left-0 h-full w-full opacity-0"
                      onClick={startRecording}
                      disabled={isRecording}
                    ></button>
                  )}

                  <p className="text-medium gap-3 text-xs capitalize text-[#525252]">
                    <span>
                      {isRecording ? "Recording..." : "Record an audio"}
                    </span>
                    {isRecording && (
                      <button
                        className="ml-3 h-4 w-4 bg-red-500"
                        onClick={stopRecording}
                        disabled={!isRecording}
                      ></button>
                    )}
                  </p>
                </div>
                <div>
                  {resultTextarea?.length > 0 ? (
                    <div
                      className={`mt-3 flex items-center rounded-md border border-[#E0E0E0] bg-[#4F46E5] pr-1.5 text-white shadow-sm ${
                        hasRecordedAudioFile ? "flex" : "hidden"
                      }`}
                    >
                      <button
                        onClick={() => handleTranscribeBtn(transcribeType)}
                        className="disabled={transcribeLoading} px-3 text-sm"
                      >
                        {transcribeLoading ? (
                          <span className="my-1.5 flex items-center justify-center gap-1">
                            <CgSpinner className="text-[1.2rem] text-white motion-safe:animate-spin" />
                            Transcribing
                          </span>
                        ) : (
                          "Transcribe"
                        )}
                      </button>

                      {!transcribeLoading && (
                        <div className="relative">
                          <button title="Profile" className="peer">
                            <div className="flex items-center gap-3 border-l-2 border-gray-800 py-2 pl-2 pr-1">
                              <FaCaretDown />
                            </div>
                          </button>
                          <ul className="absolute right-0 top-[100%] z-20 mr-[-6px] hidden rounded-md border border-[#a8a8a8] bg-white text-sm text-[#525252] shadow-md hover:block focus:block peer-focus:block peer-focus-visible:block">
                            <li>
                              <button
                                onClick={() => setTranscribeType("append")}
                                className={` flex w-full items-center justify-center gap-2 px-6 py-2 text-base font-medium
                                ${
                                  transcribeType === "append"
                                    ? " !bg-gray-300  !text-[#130b0b]"
                                    : "!text-[#130b0b]"
                                }
                              `}
                              >
                                <FaCodeMerge />
                                <span>Append</span>
                              </button>
                            </li>
                            <li>
                              <button
                                onClick={() => setTranscribeType("replace")}
                                className={` flex w-full items-center justify-center gap-2 px-6 py-2 text-base
                                ${
                                  transcribeType === "replace"
                                    ? " !bg-gray-300  !text-[#130b0b]"
                                    : "!text-[#130b0b]"
                                }
                              `}
                              >
                                <TbReplace />
                                <span>Replace</span>
                              </button>
                            </li>
                          </ul>
                        </div>
                      )}
                    </div>
                  ) : (
                    <InteractiveButton
                      className={` mt-3 flex min-w-[150px] max-w-fit items-center justify-center self-end rounded-md bg-[#4F46E5] ${
                        transcribeLoading ? "!px-2.5" : "!px-[1.95rem]"
                      } !py-2 !leading-5 text-white shadow-sm disabled:cursor-not-allowed ${
                        hasRecordedAudioFile && isApending ? "flex" : "hidden"
                      }`}
                      loading={transcribeLoading}
                      disabled={transcribeLoading}
                      onClick={() => {
                        handleTranscribeBtn(transcribeType);
                        setIsReplacing(false);
                      }}
                    >
                      {transcribeLoading ? "Transcribing" : "Transcribe"}
                    </InteractiveButton>
                  )}
                </div>
              </div>
            </div>
          </div>

          <div>
            <p className="mt-4">Transcript:</p>
            <textarea
              value={resultTextarea}
              onChange={(e) => setResultTextarea(e.target.value)}
              className="text-medium relative mb-4 flex min-h-[150px] w-full flex-col items-center justify-center rounded-lg border border-[#a8a8a8] bg-[#f4f4f4] p-5 text-[#525252]"
            ></textarea>
            <div className="flex items-center gap-4">
              <button
                onClick={handleSaveTranscribe}
                className="w-[12rem] rounded-md bg-[#4F46E5] px-3 py-2 text-center text-white shadow-sm"
              >
                {saveTranscribeLoading ? (
                  <span className="flex items-center justify-center gap-2">
                    <CgSpinner className="text-[1.2rem] text-white motion-safe:animate-spin" />
                    Saving...
                  </span>
                ) : (
                  "Save Transcription"
                )}
              </button>
            </div>
          </div>

          <div className={`mb-3 flex items-end justify-between space-x-2`}>
            <div className="flex flex-col gap-4">
              {/* <div> */}

              {/* </div> */}
            </div>
            <div></div>
          </div>
        </div>
      )}
      <div>
        <Modal
          isOpen={isCreateSection}
          onRequestClose={closeModal}
          style={customStyles}
          contentLabel="Example Modal"
        >
          <div className="mb-10 min-h-[40vh] min-w-[40vw]">
            <h5 className="my-7 text-center text-2xl font-bold capitalize">
              Add a New Section
            </h5>
            <div className="mx-auto flex w-5/6 flex-col">
              <div>
                <label htmlFor="section_name" className="text-sm text-gray-700">
                  Section Name
                </label>
                <input
                  id="section_name"
                  placeholder="Section Name"
                  value={sectionName}
                  onChange={(event) => setSectionName(event.target.value)}
                  type="text"
                  className="mb-3.5 w-full rounded-md border border-[#C6C6C6] shadow-sm hover:bg-[#f4f4f4]"
                />
              </div>
              <div>
                <label htmlFor="description" className="text-sm text-gray-700">
                  Section Description
                </label>
                <input
                  id="description"
                  placeholder="Section Description"
                  value={sectionDescription}
                  onChange={(event) =>
                    setSectionDescription(event.target.value)
                  }
                  type="text"
                  className="mb-3.5 w-full rounded-md border border-[#C6C6C6] shadow-sm hover:bg-[#f4f4f4]"
                />
              </div>

              <div className="mt-5 flex items-center justify-between gap-6">
                <button
                  onClick={closeModal}
                  className=" rounded-md bg-gray-600 px-6 py-2 text-center text-white shadow-sm"
                >
                  Cancel
                </button>
                <button
                  onClick={handleSaveSection}
                  className=" rounded-md bg-[#4F46E5] px-6 py-2 text-center text-white shadow-sm"
                >
                  Create
                </button>
              </div>
            </div>
          </div>
        </Modal>
      </div>
    </>
  );
};

export default Transcribe;
