import "./toolbar.css";
import React, { useState, useEffect } from "react";
import { UserList } from "../UserList/UserList";
import { FullscreenButton } from "../ui/FullscreenButton/FullscreenButton";
import { PopupShare } from "../PopupShare/PopupShare";
import { ExitPopup } from "../ExitPopup/ExitPopup";
import { ControlPanel } from "../ControlPanel/ControlPanel";
import { AnimatePresence, motion } from "framer-motion";
import { sidebarVariants, popupAnimation } from "../../utils/animationProps";


export const Sidebar: React.FC<any> = ({ closeStream }) => {
  const [open, setOpen] = useState(true);
  const [popup, setPopup] = useState({
    popup1: false,
    popup2: false,
  });

  const [selected, setSelected] = useState(false);

  const [isMuted, setMuted] = useState(true);

  const handleMuteClick = () => {
    setMuted((prev) => !prev);
  };

  function handleClosePopups() {
    setPopup({
      popup1: false,
      popup2: false,
    });
  }

  function handleOpenSharePopup() {
    setPopup({
      popup1: true,
      popup2: false,
    });
  }

  function handleOpenExitPopup() {
    setPopup({
      popup1: false,
      popup2: true,
    });
  }

  function closeSideBar() {
    setOpen((prev) => !prev);
    setSelected(false);
  }

  useEffect(() => () => unmountComponent(), []);

  function unmountComponent() {
    setOpen(false);
    setPopup({
      popup1: false,
      popup2: false,
    });
  }


  return (
    <div>
      <motion.div
        animate={open ? "open" : "closed"}
        variants={sidebarVariants}
        className="toolbar-container"
      >
        <div className="toolbar-field">
          <div className="toolbar-field-part">
            <FullscreenButton></FullscreenButton>
            <UserList selected={selected} setSelected={setSelected}></UserList>
          </div>
          <ControlPanel
            isMuted={isMuted}
            handleMuteClick={handleMuteClick}
            handleOpenSharePopup={handleOpenSharePopup}
            handleOpenExitPopup={handleOpenExitPopup}
          ></ControlPanel>
        </div>
        <div onClick={closeSideBar} className="toolbar-open-button">
          <span className="toolbar-open-button-icon"></span>
        </div>
      </motion.div>
      <AnimatePresence>
        {popup.popup1 && (
          <motion.div
            key={1}
            variants={popupAnimation}
            initial={"hidden"}
            animate={"show"}
            exit={"hidden"}
          >
            <PopupShare setClose={handleClosePopups}></PopupShare>
          </motion.div>
        )}

        {popup.popup2 && (
          <motion.div
            key={2}
            variants={popupAnimation}
            initial={"hidden"}
            animate={"show"}
            exit={"hidden"}
          >
            <ExitPopup
              onExit={closeStream}
              setClose={handleClosePopups}
            ></ExitPopup>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
};
