import { __ } from "@wordpress/i18n";
import { Button, ButtonGroup, Modal } from "@wordpress/components";
import { useState, useEffect, useRef, useCallback } from "@wordpress/element";
import { update } from "@wordpress/icons";

export function StickyHoverTab({ activeStateTab, setActiveStateTab, onSyncAll }) {
  const wrapperRef = useRef(null);
  const tabRef = useRef(null);
  const scrollContainerRef = useRef(null);
  const savedScrollPositionRef = useRef(null);
  const [stickyState, setStickyState] = useState({ isSticky: false, top: 0, left: 0, width: 0, offsetTop: 0 });
  const [isFadingOut, setIsFadingOut] = useState(false);
  const [showSyncConfirmModal, setShowSyncConfirmModal] = useState(false);
  const prevStickyRef = useRef(false);

  useEffect(() => {
    if (!wrapperRef.current) return;

    const scrollContainer = wrapperRef.current.closest(".interface-complementary-area.editor-sidebar");
    if (!scrollContainer) return;

    scrollContainerRef.current = scrollContainer;

    const updateStickyState = () => {
      if (!wrapperRef.current || !tabRef.current) return;

      const containerRect = scrollContainer.getBoundingClientRect();
      const wrapperRect = wrapperRef.current.getBoundingClientRect();
      const tabHeight = tabRef.current.offsetHeight;

      let fixedHeadersHeight = 0;
      const sidebarHeader = scrollContainer.querySelector(".interface-complementary-area-header");
      if (sidebarHeader) fixedHeadersHeight += sidebarHeader.offsetHeight;

      const previewDeviceControl = scrollContainer.querySelector(".zenblocks-preview-device-control");
      if (previewDeviceControl) fixedHeadersHeight += previewDeviceControl.offsetHeight;

      const parentPanel = wrapperRef.current.closest(".custom-collapsible-panel");
      let parentPanelTop = -Infinity;
      let parentPanelBottom = Infinity;
      let panelToggleHeight = 0;

      if (parentPanel) {
        const panelToggle = parentPanel.querySelector(".custom-panel-toggle");
        if (panelToggle) {
          panelToggleHeight = panelToggle.offsetHeight;
          const panelToggleRect = panelToggle.getBoundingClientRect();
          parentPanelTop = panelToggleRect.bottom;
        }
        parentPanelBottom = parentPanel.getBoundingClientRect().bottom;
      }

      const stickyThreshold = containerRect.top + fixedHeadersHeight + panelToggleHeight - 1;
      const tabTop = wrapperRect.top;
      const shouldBeSticky = tabTop < stickyThreshold && parentPanelBottom > stickyThreshold + tabHeight + 20;

      if (prevStickyRef.current && !shouldBeSticky) {
        setIsFadingOut(true);
        setTimeout(() => {
          setIsFadingOut(false);
          setStickyState({
            isSticky: false,
            top: stickyThreshold,
            left: containerRect.left,
            width: containerRect.width,
            offsetTop: fixedHeadersHeight + panelToggleHeight,
          });
        }, 200);
      } else if (!prevStickyRef.current && shouldBeSticky) {
        setIsFadingOut(false);
        setStickyState({
          isSticky: shouldBeSticky,
          top: stickyThreshold,
          left: containerRect.left,
          width: containerRect.width,
          offsetTop: fixedHeadersHeight + panelToggleHeight,
        });
      } else {
        setStickyState(prev => ({
          ...prev,
          top: stickyThreshold,
          left: containerRect.left,
          width: containerRect.width,
          offsetTop: fixedHeadersHeight + panelToggleHeight,
        }));
      }
      prevStickyRef.current = shouldBeSticky;
    };

    const handleScroll = () => requestAnimationFrame(updateStickyState);
    const handleResize = () => requestAnimationFrame(updateStickyState);

    scrollContainer.addEventListener("scroll", handleScroll, { passive: true });
    window.addEventListener("resize", handleResize);
    requestAnimationFrame(updateStickyState);

    return () => {
      scrollContainer.removeEventListener("scroll", handleScroll);
      window.removeEventListener("resize", handleResize);
    };
  }, []);

  const handleTabSwitch = useCallback(
    (newTab) => {
      if (!scrollContainerRef.current) return;

      savedScrollPositionRef.current = scrollContainerRef.current.scrollTop;

      setActiveStateTab(newTab);

      requestAnimationFrame(() => {
        if (scrollContainerRef.current && savedScrollPositionRef.current !== null) {
          scrollContainerRef.current.scrollTop = savedScrollPositionRef.current;
        }
      });
    },
    [setActiveStateTab]
  );

  const stickyStyles = (stickyState.isSticky || isFadingOut)
    ? {
        position: "fixed",
        top: stickyState.top,
        left: stickyState.left,
        width: stickyState.width,
        zIndex: 510,
        background: "#fff",
        opacity: isFadingOut ? 0 : 1,
        transition: "opacity 200ms ease-out",
      }
    : {};

  return (
    <div ref={wrapperRef}>
      {(stickyState.isSticky || isFadingOut) && <div style={{ height: tabRef.current?.offsetHeight || 53 }} />}
      <div ref={tabRef} className="zenblocks-tab-head-hover" style={stickyStyles}>
        <ButtonGroup style={{ display: "flex", width: "100%", gap: "4px" }}>
          <Button variant={activeStateTab === "normal" ? "primary" : "secondary"} onClick={() => handleTabSwitch("normal")} style={{ flex: "1 1 50%" }}>
            {__("Default", "zenblocks")}
          </Button>
          <div style={{ flex: "1 1 50%", position: "relative" }}>
            <Button variant={activeStateTab === "hover" ? "primary" : "secondary"} onClick={() => handleTabSwitch("hover")} style={{ width: "100%" }}>
              {__("Hover", "zenblocks")}
            </Button>
            {onSyncAll && (
              <Button
                className="zenblocks-hover-tab-sync-button"
                label={__("Sync Settings", "zenblocks")}
                showTooltip
                tooltipPosition="top"
                onClick={(e) => {
                  e.preventDefault();
                  e.stopPropagation();
                  setShowSyncConfirmModal(true);
                }}
              >
                <span style={{ width: "14px", height: "14px", display: "flex", alignItems: "center", justifyContent: "center" }}>{update}</span>
              </Button>
            )}
          </div>
        </ButtonGroup>
      </div>
      {showSyncConfirmModal && (
        <Modal
          title={__("Sync Hover Styles", "zenblocks")}
          onRequestClose={() => setShowSyncConfirmModal(false)}
          className="zenblocks-sync-confirm-modal"
        >
          <p style={{ marginBottom: "16px" }}>
            {__("Copy default style values to hover styles.", "zenblocks")}
          </p>
          <p style={{ marginBottom: "16px", color: "#757575", fontSize: "12px" }}>
            {__("Current hover style settings will be overwritten. This action cannot be undone.", "zenblocks")}
          </p>
          <div style={{ display: "flex", justifyContent: "flex-end", gap: "8px" }}>
            <Button variant="secondary" onClick={() => setShowSyncConfirmModal(false)}>
              {__("Cancel", "zenblocks")}
            </Button>
            <Button
              variant="primary"
              onClick={() => {
                onSyncAll();
                setShowSyncConfirmModal(false);
              }}
            >
              {__("Sync", "zenblocks")}
            </Button>
          </div>
        </Modal>
      )}
    </div>
  );
}

export default StickyHoverTab;
