import { message } from "antd";
import { produce } from "immer";
import { AnimatePresence, motion } from "motion/react";
import { useContext, useEffect, useRef, useState } from "react";
import tooltipImg2 from "~/assets/images/map_bi/right_utils/branch_office/bg11.png";
import buttonBg from "~/assets/images/map_bi/right_utils/branch_office/button.png";
import tooltipImg1 from "~/assets/images/map_bi/right_utils/port/tooltip.png";
import { Context } from "~/pages/Container/Map/js/context";
import { utilsList } from "./utilsList";
import "./index.less";

const rightUtilsAnimation = {
  initial: { x: 100, opacity: 0 },
  animate: { x: 0, opacity: 1, transition: { duration: 0.5, ease: "easeOut" } },
  exit: { x: 100, opacity: 0, transition: { duration: 0.3, ease: "easeIn" } },
};

const childMenuAnimation = {
  visible: {
    y: [80, -15, 5, 0],
    opacity: [0, 1, 1, 1],
    scale: [0.9, 1.05, 0.98, 1],
    transition: { duration: 0.7, times: [0, 0.5, 0.75, 1], ease: [0.34, 1.56, 0.64, 1] },
  },
  hidden: {
    y: [0, -20, 10, 100],
    opacity: [1, 1, 0.8, 0],
    scale: [1, 1.02, 0.95, 0.85],
    transition: { duration: 0.5, times: [0, 0.2, 0.5, 1], ease: [0.68, -0.6, 0.32, 1.6] },
  },
};

function RightUtils(props) {
  const {
    currentPort,
    mapMethods,
    pureMap,
    currentBranchOffice,
    bottomUtilsCurrentIndex,
    rightUtilsResetVersion,
    actions,
  } = useContext(Context);

  const [list, setList] = useState(utilsList);
  const [isShowChildLevel, setIsShowChildLevel] = useState(true);
  const childMenuAnimationLockRef = useRef(true);
  const [isChildMenuAnimating, setIsChildMenuAnimating] = useState(true);
  const rightUtilsMode = currentPort && !currentBranchOffice
    ? "port"
    : currentBranchOffice && bottomUtilsCurrentIndex !== -1 ? "branchOffice" : null;

  useEffect(() => {
    if (bottomUtilsCurrentIndex === -1)
      setIsShowChildLevel(true);
  }, [bottomUtilsCurrentIndex]);

  useEffect(() => {
    setList(produce((draft) => {
      draft.forEach((item) => {
        if (item.type === "fourColor" || item.type === "wall")
          item.check = false;
      });
    }));
  }, [rightUtilsResetVersion]);

  useEffect(() => {
    setList(produce((draft) => {
      draft.forEach((item) => {
        if (item.type === "full")
          item.check = props.isFullscreen;
      });
    }));
  }, [props.isFullscreen]);

  const clickRightTools = (index, type) => {
    let check;
    if (list[index].check !== undefined) {
      check = !list[index].check;
      setList(produce((draft) => {
        draft[index].check = check;
      }));
    }

    switch (type) {
      case "back":
        window.close();
        setTimeout(() => {
          if (!window.closed && !window.opener) {
            window.location.href = "https://gbs-gateway.qhdsafety.com/";
          }
        }, 500);
        break;
      case "full":
        props.toggleFullscreen();
        break;
      case "return":
        mapMethods.current.returnCurrentCenterPoint();
        break;
      case "scene":
        mapMethods.current.changeSceneMode(check ? "2d" : "3d");
        break;
      case "del":
        mapMethods.current.removeMarkPoint();
        actions.resetBottomUtils();
        break;
      case "pureMap":
        actions.setPureMap(!pureMap);
        break;
      case "weather":
        actions.selectMark({ title: "气象监测", markType: "meteorologicalMonitoring" });
        break;
      case "fourColor":
        if (!currentPort) {
          message.warning("请选择要查看的港口");
          setList(produce((draft) => {
            draft[index].check = false;
          }));
          return;
        }
        if (check) {
          mapMethods.current.addFourColorDiagram(
            currentPort,
            currentBranchOffice,
          );
        }
        else {
          mapMethods.current.removeFourColorDiagram();
        }
        break;
      case "wall":
        if (!currentPort) {
          message.warning("请选择要查看的港口");
          setList(produce((draft) => {
            draft[index].check = false;
          }));
          return;
        }
        if (check)
          mapMethods.current.addWall(currentPort, currentBranchOffice);
        else mapMethods.current.removeWall();
        break;
    }
  };

  const renderPortUtils = () => {
    if (rightUtilsMode === "port") {
      return (
        <>
          {list.map((item, index) => (
            <div
              key={index}
              className="option"
              onClick={() => clickRightTools(index, item.type)}
            >
              <div style={{ backgroundImage: `url(${tooltipImg1})` }} className="tooltip">{item.label}</div>
              <img src={item.check ? item.checkImgPort : item.imgPort} alt="" />
            </div>
          ))}
        </>
      );
    }
    return null;
  };

  const renderBranchOfficeUtils = () => {
    if (rightUtilsMode === "branchOffice") {
      return (
        <>
          <motion.div
            className="options"
            initial="hidden"
            animate={isShowChildLevel ? "visible" : "hidden"}
            variants={childMenuAnimation}
            onAnimationStart={() => {
              childMenuAnimationLockRef.current = true;
              setIsChildMenuAnimating(true);
            }}
            onAnimationComplete={() => {
              childMenuAnimationLockRef.current = false;
              setIsChildMenuAnimating(false);
            }}
          >
            {list.map((item, index) => (
              <div
                key={index}
                className={`option ${item.check ? "active" : ""}`}
                onClick={() => clickRightTools(index, item.type)}
              >
                <div style={{ backgroundImage: `url(${tooltipImg2})` }} className="tooltip">{item.label}</div>
                <img src={item.imgBranchOffice} alt="" />
              </div>
            ))}
          </motion.div>
          <div
            className={`bg ${isShowChildLevel ? "active" : ""} ${isChildMenuAnimating ? "disabled" : ""}`}
            aria-disabled={isChildMenuAnimating}
            onClick={() => {
              if (childMenuAnimationLockRef.current)
                return;
              // 点击时同步占用锁，避免等待下一次渲染期间发生连续点击。
              childMenuAnimationLockRef.current = true;
              setIsChildMenuAnimating(true);
              setIsShowChildLevel(visible => !visible);
            }}
          >
            <img src={buttonBg} alt="" />
          </div>
        </>
      );
    }
    return null;
  };

  return (
    <div className="map_content_right_utils_container">
      <AnimatePresence mode="wait">
        {rightUtilsMode && (
          <motion.div
            key={rightUtilsMode}
            className={rightUtilsMode === "port" ? "right_utils port" : "right_utils branch_office"}
            {...rightUtilsAnimation}
          >
            {renderPortUtils()}
            {renderBranchOfficeUtils()}
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}

export default RightUtils;
