import { AnimatePresence, motion } from "motion/react";
import { useContext, useEffect, useState } from "react";
import collapseMenuImg1 from "~/assets/images/map_bi/content/collapse_menu1.png";
import collapseMenuImg2 from "~/assets/images/map_bi/content/collapse_menu2.png";
import collapseMenuBg1 from "~/assets/images/map_bi/content/collapse_menu_bg1.png";
import collapseMenuBg2 from "~/assets/images/map_bi/content/collapse_menu_bg2.png";
import { branchOfficeUtilsList } from "~/pages/Container/Map/components/BottomUtils/branchOfficeUtilsList";
import { portUtilsList } from "~/pages/Container/Map/components/BottomUtils/portUtilsList";
import BranchCamera from "~/pages/Container/Map/components/Content/branchOffice/Camera";
import BranchFengBi from "~/pages/Container/Map/components/Content/branchOffice/FengBi";
import BranchOfficeIndexLeft from "~/pages/Container/Map/components/Content/branchOffice/IndexLeft";
import BranchOfficeIndexRight from "~/pages/Container/Map/components/Content/branchOffice/IndexRight";
import BranchMenJin from "~/pages/Container/Map/components/Content/branchOffice/MenJin";
import BranchQiXiang from "~/pages/Container/Map/components/Content/branchOffice/QiXiang";
import BranchRenYuan from "~/pages/Container/Map/components/Content/branchOffice/RenYuan";
import BranchWeiXian from "~/pages/Container/Map/components/Content/branchOffice/WeiXian";
import BranchXiaoFang from "~/pages/Container/Map/components/Content/branchOffice/XiaoFang";
import BranchZhongDian from "~/pages/Container/Map/components/Content/branchOffice/ZhongDian";
import IndexInfo from "~/pages/Container/Map/components/Content/IndexInfo";
import PortFengBi from "~/pages/Container/Map/components/Content/port/FengBi";
import PortIndex from "~/pages/Container/Map/components/Content/port/Index";
import PortMenJin from "~/pages/Container/Map/components/Content/port/MenJin";
import PortQiXiang from "~/pages/Container/Map/components/Content/port/QiXiang";
import PortRenYuan from "~/pages/Container/Map/components/Content/port/RenYuan";
import PortWeiXian from "~/pages/Container/Map/components/Content/port/WeiXian";
import PortXiaoFang from "~/pages/Container/Map/components/Content/port/XiaoFang";
import PortZhongDian from "~/pages/Container/Map/components/Content/port/ZhongDian";
import { Context } from "~/pages/Container/Map/js/context";
import "./index.less";

const indexAnimation = {
  initial: { scale: 0.8, opacity: 0 },
  animate: { scale: 1, opacity: 1, transition: { duration: 0.5, ease: "easeOut" } },
  exit: { scale: 0.8, opacity: 0, transition: { duration: 0.3, ease: "easeIn" } },
};

const panelAnimation = side => ({
  initial: { x: side === "left" ? -300 : 300, opacity: 0 },
  animate: { x: 0, opacity: 1, transition: { duration: 0.5, ease: "easeOut" } },
  exit: { x: side === "left" ? -300 : 300, opacity: 0, transition: { duration: 0.3, ease: "easeIn" } },
});

function Content(props) {
  const { currentPort, currentBranchOffice, pureMap, bottomUtilsCurrentIndex, portArea } = useContext(Context);
  const [isLeftCollapsed, setIsLeftCollapsed] = useState(false);
  const [isRightCollapsed, setIsRightCollapsed] = useState(false);

  const bottomUtilsCurrentType = currentBranchOffice
    ? branchOfficeUtilsList[bottomUtilsCurrentIndex]?.type || ""
    : portUtilsList[bottomUtilsCurrentIndex]?.type || "";
  const contentKey = `${currentPort}_${currentBranchOffice}_${bottomUtilsCurrentIndex}_${portArea}`;
  const pageKey = `${currentPort}_${currentBranchOffice}`;
  const isPortContent = currentPort === "00003" && !currentBranchOffice;
  const [leftButtonKey, setLeftButtonKey] = useState(bottomUtilsCurrentIndex);
  const [rightButtonKey, setRightButtonKey] = useState(bottomUtilsCurrentIndex);
  const leftAnimationKey = isLeftCollapsed ? leftButtonKey : bottomUtilsCurrentIndex;
  const rightAnimationKey = isRightCollapsed ? rightButtonKey : bottomUtilsCurrentIndex;

  // 页面层级直接包含在 animation key 中；底部操作栏变化时，仅展开状态的按钮更新 key。
  useEffect(() => {
    if (!isLeftCollapsed)
      setLeftButtonKey(bottomUtilsCurrentIndex);
    if (!isRightCollapsed)
      setRightButtonKey(bottomUtilsCurrentIndex);
  }, [bottomUtilsCurrentIndex]);

  const renderPortContent = () => {
    const contentMap = {
      "": PortIndex,
      "camera": PortIndex,
      "door": PortMenJin,
      "fire": PortXiaoFang,
      "danger": PortWeiXian,
      "weather": PortQiXiang,
      "people": PortRenYuan,
      "keyProject": PortZhongDian,
      "closedArea": PortFengBi,
    };
    const Component = contentMap[bottomUtilsCurrentType];
    return Component ? <Component /> : null;
  };

  const renderBranchOfficeContentLeft = () => {
    const contentMap = {
      "": BranchOfficeIndexLeft,
      "danger": BranchWeiXian,
      "door": BranchMenJin,
      "fire": BranchXiaoFang,
      "people": BranchRenYuan,
      "weather": BranchQiXiang,
      "keyProject": BranchZhongDian,
      "closedArea": BranchFengBi,
      "camera": BranchCamera,
    };
    const Component = contentMap[bottomUtilsCurrentType];
    return Component ? <Component /> : null;
  };

  const renderCollapseButton = ({ side, isCollapsed, setIsCollapsed, animationKey }) => {
    const isPort = isPortContent;
    const collapsedX = side === "left" ? -465 : 465;
    const hiddenX = side === "left" ? -600 : 600;
    const containerRotation = !isPort && side === "right" ? 180 : 0;
    const imageRotation = isPort
      ? (isCollapsed ? 180 : 0)
      : (isCollapsed ? 0 : 180);

    return (
      <motion.div
        key={animationKey}
        className={`collapse_menu ${isPort ? "port" : "branch_office"} ${side}`}
        style={{ backgroundImage: `url(${isPort ? collapseMenuBg1 : collapseMenuBg2})` }}
        initial={{ x: hiddenX, opacity: 0, rotate: containerRotation }}
        animate={{
          x: isCollapsed ? collapsedX : 0,
          opacity: 1,
          rotate: containerRotation,
          transition: { duration: 0.5, ease: "easeOut" },
        }}
        exit={{
          x: hiddenX,
          opacity: 0,
          rotate: containerRotation,
          transition: { duration: 0.3, ease: "easeIn" },
        }}
        onClick={() => setIsCollapsed(value => !value)}
      >
        <motion.img
          src={isPort ? collapseMenuImg1 : collapseMenuImg2}
          alt=""
          animate={{ x: "-50%", y: "-50%", rotate: imageRotation }}
          transition={{ duration: isCollapsed ? 0.3 : 0.5, ease: isCollapsed ? "easeIn" : "easeOut" }}
          style={{ left: "50%", top: "50%", position: "absolute" }}
        />
      </motion.div>
    );
  };

  return (
    <div className="map_content_container">
      <AnimatePresence mode="wait">
        {!currentPort && !currentBranchOffice && (
          <motion.div key="index" className="map_content_container__indexinfo" {...indexAnimation}>
            <IndexInfo history={props.history} />
          </motion.div>
        )}
      </AnimatePresence>

      <AnimatePresence mode="wait">
        {!pureMap && !isLeftCollapsed && (isPortContent || currentBranchOffice) && (
          <motion.div
            key={`left_${contentKey}`}
            className={`map_content_container__content ${isPortContent ? "port" : "branch_office"}`}
            style={{ left: 35 }}
            {...panelAnimation("left")}
          >
            {isPortContent ? renderPortContent() : renderBranchOfficeContentLeft()}
          </motion.div>
        )}
      </AnimatePresence>

      <AnimatePresence mode="wait">
        {!pureMap && !isRightCollapsed && currentBranchOffice && (
          <motion.div
            key={`right_${contentKey}`}
            className="map_content_container__content branch_office"
            style={{ right: 35 }}
            {...panelAnimation("right")}
          >
            {bottomUtilsCurrentType === "" && <BranchOfficeIndexRight />}
          </motion.div>
        )}
      </AnimatePresence>

      <AnimatePresence mode="wait">
        {!pureMap && (isPortContent || (currentBranchOffice && (bottomUtilsCurrentType !== "camera" || isLeftCollapsed)))
          && renderCollapseButton({
            side: "left",
            isCollapsed: isLeftCollapsed,
            setIsCollapsed: setIsLeftCollapsed,
            animationKey: `left_${pageKey}_${leftAnimationKey}`,
          })}
      </AnimatePresence>

      <AnimatePresence mode="wait">
        {!pureMap && currentBranchOffice && bottomUtilsCurrentIndex === -1
          && renderCollapseButton({
            side: "right",
            isCollapsed: isRightCollapsed,
            setIsCollapsed: setIsRightCollapsed,
            animationKey: `right_${pageKey}_${rightAnimationKey}`,
          })}
      </AnimatePresence>
    </div>
  );
}

export default Content;
