import React, {
  useCallback,
  useContext,
  useEffect,
  useLayoutEffect,
  useRef,
  useState,
} from 'react';
import { EmojiIcon } from '../../../assets/svg/emoji';
import { GalleryIcon } from '../../../assets/svg/gallery';
import { MicrophoneIcon } from '../../../assets/svg/microphone';
import { SendIcon } from '../../../assets/svg/send';
import { TextMessagePanel } from '../messages/index.styled';
import Picker from 'emoji-picker-react';
import cx from 'classnames';
import { ReactMic } from 'react-mic';
import WaveSurfer from 'wavesurfer.js';
import moment from 'moment';
import { RecorderIcon } from '../../../assets/svg/recorder';
import { RecorderPlayIcon } from '../../../assets/svg/recorderPlay';
import { PauseIcon } from '../../../assets/svg/pause';
import { Bin } from '../../../assets/svg/bin';
import useMessaging from '../hooks/useMessaging';
import useMedia from '../hooks/useMedia';
import { getCookie } from '../utils/helpers';
import InputEmoji from 'react-input-emoji';
import { useLocation } from 'react-router-dom';
import MessagesContext from '../hooks/messagesContext';

/** The input section of an open chat, for sending texts, emojis and audios
 *
 */
import useTranslation from "../../../hooks/useTranslation.jsx";
import wordStore from "../../../mc/wordStore.json";
const InputSection = ({
  userID,
  setPreviewModalIsOpen,
  mediaForm,
  setMediaForm,
  setAllMessages,
  allMessages,
  newMessages,
  setNewMessages,
  setIsMessageSending,
  accountType,
  affiliates,
  courseID,
  handleCreateMessage,
  createMessageData,
  enterpriseAffiliateID,
  receiverID,
}) => {
  const { findText } = useTranslation(wordStore);
  const [showEmoji, setShowEmoji] = useState();
  const [inputMethod, setInputMethod] = useState('text'); // text | recorder
  const [text, setText] = useState({
    text: '',
    // user_message: true
  }); // state for user text
  const [blobData, setBlobData] = useState({}); //state for audio
  const [recording, setRecording] = useState(false);
  const [isPlaying, setIsPlaying] = useState(false);
  const [successResponse, setSuccessResponse] = useState(false);
  const {
    handleCreateMessageWithMedia,
    createMessageWithMediaData,
    createMessageAffiliateData,
    handleCreateMessageAffiliate,
    createMessagePersonalData,
    handleCreateMessagePersonal,
  } = useMessaging();
  const { handleUploadMedia, uploadMediaData } = useMedia();

  // console.log(text);

  // Handle Send when Enter key pressed
  const handleEnterKey = (e) => {
    if (e.key === 'Enter') {
      handleSendMessage();
    }
  };

  // handle sending a text and audio when button clicked
  const handleSendMessage = (e) => {
    if (inputMethod === 'recorder') {
      //   const file = new File([blobData.blob], `record-${Date.now()}.wav`);
      const file = new File([blobData.blob], `record-${Date.now()}.wav`, {
        type: 'audio/wav',
      });
      const data = {
        media: file,
      };
      // handleCreateMessageWithMedia(data.media, receiverID);
      handleCreateMessageWithMedia(
        receiverID,
        accountType,
        data.media,
        courseID,
        enterpriseAffiliateID,
      );
      setInputMethod('text');
      //console.log("uploas", file);
    }
    if (inputMethod === "text") {
      // setNewMessages((prev) => [...prev, text]);
      setIsMessageSending(true);
      setTimeout(() => {
        handleCreateMessage(
          receiverID,
          accountType,
          text,
          courseID,
          enterpriseAffiliateID,
        );
      }, 1000);
    }
  };

  //console.log("createMessageData", createMessageData);

  // handle open modal for image preview when an image selected (future note)
  useEffect(() => {
    if (mediaForm?.media) {
      setPreviewModalIsOpen(true);
    }
  }, [mediaForm]);

  //handle update messages state when a message sent successfully for text and audio
  useEffect(() => {
    if (createMessageData?.response?.status === 201) {
      setNewMessages((prev) => [...prev, createMessageData?.data]);
      // newMessages[newMessages.length - 1] = createMessageData?.data;
      setIsMessageSending(false);
      setText({
        ...text,
        text: '',
      });
    }
    if (createMessageAffiliateData?.response?.status === 201) {
      setNewMessages((prev) => [...prev, createMessageAffiliateData?.data]);
      // newMessages[newMessages.length - 1] = createMessageData?.data;
      setIsMessageSending(false);
      setText({
        ...text,
        text: '',
      });
    }
    if (createMessagePersonalData?.response?.status === 201) {
      setNewMessages((prev) => [...prev, createMessagePersonalData?.data]);
      // newMessages[newMessages.length - 1] = createMessageData?.data;
      setIsMessageSending(false);
      setText({
        ...text,
        text: '',
      });
    }
  }, [
    createMessageData?.response,
    createMessageAffiliateData?.response,
    createMessagePersonalData?.response,
  ]);
  useEffect(() => {
    if (createMessageWithMediaData?.response?.status === 201) {
      setNewMessages((prev) => [...prev, createMessageWithMediaData?.data]);
      // newMessages[newMessages.length - 1] = createMessageData?.data;
      setText({
        ...text,
        text: '',
      });
    }
  }, [createMessageWithMediaData?.response]);

  //handle update messages state when a message sent successfully for text and audio ends here

  // console.log("media", mediaForm);
  // console.log("media2", uploadMediaData);
  // console.log("media3", imageRef);

  return (
    <TextMessagePanel>
      <div
        className={cx('text-input-wrapper', {
          'text-mode': inputMethod === 'text',
        })}
      >
        {inputMethod === 'text' && (
          <>
            <div className="icon-box">
              <>
                {/* for handling sending of media (future note) */}
                {/* <span onClick={(e) => imageRef.current.click()}>
                 <GalleryIcon />
                 </span>
                 <input
                 ref={imageRef}
                 type="file"
                 accept="image/*"
                 style={{ display: "none" }}
                 onChange={async (e) => {
                  console.log("media", e);
                  if (e.target.files) {
                    const file = e.target.files[0];
                    let imageDataUrl = await readFile(file);
                    setMediaForm({
                      ...mediaForm,
                      media: e.target.files[0],
                    });
                  }
                 }}
                 /> */}
              </>
              <span
                onClick={(e) => {
                  setInputMethod('recorder');
                }}
              >
                <MicrophoneIcon />
              </span>
            </div>

            <InputEmoji
              value={text.text}
              cleanOnEnter
              onEnter={handleSendMessage}
              placeholder={findText("Start typing...")}
              onChange={(e) => {
                setText((prev) => ({
                  ...prev,
                  text: e,
                }));
              }}
              theme={findText("light")}
            />
          </>
        )}
        {inputMethod === 'recorder' && (
          <>
            <Recorder
              {...{
                setInputMethod,
                blobData,
                setBlobData,
                recording,
                setRecording,
                isPlaying,
                setIsPlaying,
              }}
            />
          </>
        )}
      </div>
      <button
        className={findText("send-box {arg1}", {
          arg1:
            (!text.text && inputMethod !== "recorder") ||
            createMessageData?.loading ||
            recording
              ? "disabled"
              : "",
        })}
        onClick={handleSendMessage}
        disabled={
          (!text.text && inputMethod !== 'recorder') ||
          createMessageData?.loading ||
          recording
        }
      >
        <SendIcon />
      </button>
    </TextMessagePanel>
  );
};

/** For audio recording and waves functionality
 *
 */
const Recorder = ({
  blobData,
  setBlobData,
  setInputMethod,
  recording,
  setRecording,
  isPlaying,
  setIsPlaying,
}) => {
  const [recordingTime, setRecordingTime] = useState(0);
  const waveSurfer = useRef(null);
  const counterRef = useRef();
  const [pausedTime, setPausedTime] = useState(0);
  console.log("blob", blobData);

  // Reset everything when clicking Bin
  const clearRecording = () => {
    if (waveSurfer.current) {
      waveSurfer.current.stop();
      waveSurfer.current.empty();
    }
    setBlobData({
      blob: null,
      url: null,
    });
    setRecording(false);
    setIsPlaying(false);
    setRecordingTime(0);
    setPausedTime(0);
    setInputMethod('text');
  };

  // Concatenate blobs for pause & continue recording
  const handleStop = (data) => {
    const { blob } = data;
    setBlobData((prevState) => {
      const newBlob = prevState.blob
        ? new Blob([prevState.blob, blob], {
            type: "audio/wav",
          })
        : blob;
      const url = URL.createObjectURL(newBlob);
      return {
        blob: newBlob,
        url,
      };
    });
  };
  useLayoutEffect(() => {
    setRecording(true);
  }, []);

  // Handle recording time counter
  useEffect(() => {
    if (recording) {
      let time = pausedTime;
      counterRef.current = setInterval(() => {
        time++;
        setRecordingTime(time);
      }, 1000);
    } else {
      clearInterval(counterRef.current);
      setPausedTime(recordingTime);
    }
    return () => clearInterval(counterRef.current);
  }, [recording]);

  // Setup WaveSurfer for playback
  useEffect(() => {
    if (blobData.blob) {
      if (!waveSurfer.current) {
        waveSurfer.current = WaveSurfer.create({
          container: '#waves-input',
          waveColor: '#E5AD0E',
          progressColor: '#FECF4C',
          cursorWidth: 0,
          height: 58,
          barWidth: 2.5,
          barGap: 4,
          barRadius: 2,
          barMinHeight: 3,
        });
      }
      waveSurfer.current.on("finish", () => setIsPlaying(false));
      waveSurfer.current.loadBlob(blobData.blob);
    }
  }, [blobData.blob]);
  return (
    <>
      <div className="left-recorder-state">
        <span className="icon">
          {(recording || isPlaying) && (
            <PauseIcon
              onClick={() => {
                if (recording) {
                  setRecording(false); // Stop recording
                } else if (isPlaying) {
                  waveSurfer.current.pause(); // Pause playback
                  setIsPlaying(false);
                }
              }}
            />
          )}

          {!recording && !isPlaying && blobData.blob && (
            <RecorderIcon
              onClick={() => {
                waveSurfer.current.play(); // Play recording
                setIsPlaying(true);
              }}
            />
          )}
        </span>

        <div className="timer">
          {moment.duration(recordingTime, 'seconds').minutes()}:
          {moment.duration(recordingTime, 'seconds').seconds()}
        </div>
      </div>

      <div className="waves-section">
        {!recording && blobData.blob && (
          <span
            className="icon"
            onClick={() => {
              waveSurfer.current.stop(); // Stop playback
              setIsPlaying(false);
              setRecording(true); // Resume recording
            }}
          >
            <RecorderPlayIcon />
          </span>
        )}
        <div id="waves-input"></div>

        {!recording && blobData.blob && (
          <span className="icon" onClick={clearRecording}>
            <Bin />
          </span>
        )}
        <div className="react-mic">
          <ReactMic
            onStop={handleStop}
            record={recording}
            mimeType="audio/wav"
          />
        </div>
      </div>
    </>
  );
};
export default InputSection;
