/**
 * FloatingSettingsPanel Component
 *
 * A floating popover panel that appears next to selected elements.
 * Features glassmorphism design, smooth animations, and cascading sub-popovers.
 */

import { useState, useEffect, useRef, useCallback } from "react";
import { motion, AnimatePresence } from "motion/react";
import * as Tabs from "@radix-ui/react-tabs";
import { Cross2Icon, GearIcon } from "@radix-ui/react-icons";

import { useCanvasStore, useSelectedElements, useIsCompactMode } from "@/stores/canvasStore";
import type {
  CanvasElement,
  PriceElement,
  ResponsiveTypographySettings,
  ResponsiveBorderSettings,
  VariablePriceRangeElement,
} from "@/types";
import { createResponsiveValue } from "@/types";
import { TypographyPopover, BordersPopover, PlaceholderPopover } from "./popovers";
import { ContentTab, StyleTab, MoreTab } from "./tabs";

// Animation variants for the floating panel
const panelVariants = {
  hidden: {
    opacity: 0,
    scale: 0.95,
    x: 20,
  },
  visible: {
    opacity: 1,
    scale: 1,
    x: 0,
    transition: {
      type: "spring",
      stiffness: 300,
      damping: 30,
    },
  },
  exit: {
    opacity: 0,
    scale: 0.95,
    x: 20,
    transition: {
      duration: 0.15,
    },
  },
};

interface FloatingSettingsPanelProps {
  /** Position relative to canvas container */
  containerRef?: React.RefObject<HTMLDivElement>;
}

export function FloatingSettingsPanel({ containerRef }: FloatingSettingsPanelProps) {
  const panelRef = useRef<HTMLDivElement>(null);
  const [typographyOpen, setTypographyOpen] = useState(false);
  const [bordersOpen, setBordersOpen] = useState(false);
  const [decimalTypographyOpen, setDecimalTypographyOpen] = useState(false);
  const [activeDecimalField, setActiveDecimalField] = useState<"decimal" | "minDecimal" | "maxDecimal">("decimal");
  const [placeholderOpen, setPlaceholderOpen] = useState(false);
  const [position, setPosition] = useState({ x: 0, y: 0 });

  const selectedElements = useSelectedElements();
  const compact = useIsCompactMode();
  const element = selectedElements.length === 1 ? selectedElements[0] : null;
  const zoom = useCanvasStore((state) => state.zoom);
  const updateElement = useCanvasStore((state) => state.updateElement);

  // Calculate panel position based on selected element
  useEffect(() => {
    if (!element || !containerRef?.current) return;

    const containerRect = containerRef.current.getBoundingClientRect();

    // Calculate element position in screen coordinates
    const elementRight = (element.position.x + element.size.width) * zoom;
    const elementTop = element.position.y * zoom;

    // Position panel to the right of the element with some offset
    const panelX = Math.min(
      elementRight + 20,
      containerRect.width - 320 // Keep panel within container
    );
    const panelY = Math.max(20, Math.min(elementTop, containerRect.height - 400));

    setPosition({ x: panelX, y: panelY });
  }, [element, containerRef, zoom]);

  // Close popovers when clicking outside
  useEffect(() => {
    const handleClickOutside = (e: MouseEvent) => {
      if (panelRef.current && !panelRef.current.contains(e.target as Node)) {
        // Don't close if clicking on canvas elements
        const target = e.target as HTMLElement;
        if (target.closest(".konvajs-content")) return;
      }
    };

    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  // Helper to handle decimal typography toggle with field tracking
  const handleDecimalTypographyToggle = useCallback((open: boolean, field?: "decimal" | "minDecimal" | "maxDecimal") => {
    setDecimalTypographyOpen(open);
    if (field) {
      setActiveDecimalField(field);
    }
  }, []);

  if (!element) return null;

  const isPriceElement = element.type === "regularPrice" || element.type === "salePrice";
  const priceElement = isPriceElement ? (element as PriceElement) : null;
  const isVariablePriceRange = element.type === "variablePriceRange";
  const rangeElement = isVariablePriceRange ? (element as VariablePriceRangeElement) : null;

  const handleUpdate = (updates: Partial<CanvasElement>) => {
    updateElement(element.id, updates);
  };

  const handleClose = () => {
    useCanvasStore.getState().clearSelection();
  };

  return (
    <AnimatePresence>
      <motion.div
        ref={panelRef}
        className="floating-settings"
        style={{
          position: "absolute",
          left: position.x,
          top: position.y,
          zIndex: 100,
        }}
        variants={panelVariants}
        initial="hidden"
        animate="visible"
        exit="exit"
      >
        {/* Main Panel */}
        <div className="floating-settings__panel">
          {/* Header */}
          <div className="floating-settings__header">
            <div className="floating-settings__title">
              <GearIcon className="w-3.5 h-3.5" />
              <span>{element.name}</span>
            </div>
            <button className="floating-settings__close" onClick={handleClose} aria-label="Close settings">
              <Cross2Icon className="w-4 h-4" />
            </button>
          </div>

          {/* Content */}
          <div className="floating-settings__content">
            <Tabs.Root defaultValue="content" className="w-full">
              <Tabs.List className="floating-settings__tabs">
                <Tabs.Trigger value="content" className="floating-settings__tab">
                  Content
                </Tabs.Trigger>
                <Tabs.Trigger value="style" className="floating-settings__tab">
                  Style
                </Tabs.Trigger>
                <Tabs.Trigger value="more" className="floating-settings__tab">
                  More
                </Tabs.Trigger>
              </Tabs.List>

              {/* Content Tab */}
              <Tabs.Content value="content" className="floating-settings__tab-content">
                <ContentTab
                  element={element}
                  onUpdate={handleUpdate}
                  compact={compact}
                  decimalTypographyOpen={decimalTypographyOpen}
                  onDecimalTypographyToggle={handleDecimalTypographyToggle}
                />
              </Tabs.Content>

              {/* Style Tab */}
              <Tabs.Content value="style" className="floating-settings__tab-content">
                <StyleTab
                  element={element}
                  onUpdate={handleUpdate}
                  typographyOpen={typographyOpen}
                  onTypographyToggle={setTypographyOpen}
                  bordersOpen={bordersOpen}
                  onBordersToggle={setBordersOpen}
                />
              </Tabs.Content>

              {/* More Tab */}
              <Tabs.Content value="more" className="floating-settings__tab-content">
                <MoreTab
                  element={element}
                  onUpdate={handleUpdate}
                  compact={compact}
                  placeholderOpen={placeholderOpen}
                  onPlaceholderToggle={setPlaceholderOpen}
                />
              </Tabs.Content>
            </Tabs.Root>
          </div>
        </div>

        {/* Cascading Typography Popover */}
        <AnimatePresence>
          {typographyOpen && (
            <TypographyPopover
              typography={element.typography}
              onUpdate={(typography: ResponsiveTypographySettings) => handleUpdate({ typography })}
              onClose={() => setTypographyOpen(false)}
            />
          )}
        </AnimatePresence>

        {/* Cascading Borders Popover */}
        <AnimatePresence>
          {bordersOpen && (
            <BordersPopover
              border={element.border}
              onUpdate={(border: ResponsiveBorderSettings) => handleUpdate({ border })}
              onClose={() => setBordersOpen(false)}
            />
          )}
        </AnimatePresence>

        {/* Cascading Decimal Typography Popover */}
        <AnimatePresence>
          {decimalTypographyOpen && isPriceElement && priceElement && (
            <TypographyPopover
              typography={{
                fontFamily: priceElement.decimal.typography?.fontFamily ?? "Inter",
                fontSize: priceElement.decimal.typography?.fontSize ?? createResponsiveValue(14),
                fontWeight: priceElement.decimal.typography?.fontWeight ?? createResponsiveValue(400),
                fontStyle: priceElement.decimal.typography?.fontStyle ?? "normal",
                lineHeight: priceElement.decimal.typography?.lineHeight ?? 1.2,
                letterSpacing: priceElement.decimal.typography?.letterSpacing ?? createResponsiveValue(0),
                textTransform: priceElement.decimal.typography?.textTransform ?? "none",
                textDecoration: priceElement.decimal.typography?.textDecoration ?? "none",
              }}
              onUpdate={(typography: ResponsiveTypographySettings) => {
                handleUpdate({
                  decimal: {
                    ...priceElement.decimal,
                    typography: {
                      fontFamily: typography.fontFamily,
                      fontSize: typography.fontSize,
                      fontWeight: typography.fontWeight,
                      fontStyle: typography.fontStyle,
                      lineHeight: typography.lineHeight,
                      letterSpacing: typography.letterSpacing,
                      textTransform: typography.textTransform,
                      textDecoration: typography.textDecoration,
                    },
                  },
                } as Partial<CanvasElement>);
              }}
              onClose={() => setDecimalTypographyOpen(false)}
              hideTextTransform
            />
          )}
        </AnimatePresence>

        {/* Cascading Decimal Typography Popover for Variable Range */}
        <AnimatePresence>
          {decimalTypographyOpen &&
            isVariablePriceRange &&
            rangeElement &&
            (activeDecimalField === "minDecimal" || activeDecimalField === "maxDecimal") && (
              <TypographyPopover
                typography={{
                  fontFamily: rangeElement[activeDecimalField].typography?.fontFamily ?? "Inter",
                  fontSize: rangeElement[activeDecimalField].typography?.fontSize ?? createResponsiveValue(14),
                  fontWeight: rangeElement[activeDecimalField].typography?.fontWeight ?? createResponsiveValue(400),
                  fontStyle: rangeElement[activeDecimalField].typography?.fontStyle ?? "normal",
                  lineHeight: rangeElement[activeDecimalField].typography?.lineHeight ?? 1.2,
                  letterSpacing: rangeElement[activeDecimalField].typography?.letterSpacing ?? createResponsiveValue(0),
                  textTransform: rangeElement[activeDecimalField].typography?.textTransform ?? "none",
                  textDecoration: rangeElement[activeDecimalField].typography?.textDecoration ?? "none",
                }}
                onUpdate={(typography: ResponsiveTypographySettings) => {
                  handleUpdate({
                    [activeDecimalField]: {
                      ...rangeElement[activeDecimalField],
                      typography: {
                        fontFamily: typography.fontFamily,
                        fontSize: typography.fontSize,
                        fontWeight: typography.fontWeight,
                        fontStyle: typography.fontStyle,
                        lineHeight: typography.lineHeight,
                        letterSpacing: typography.letterSpacing,
                        textTransform: typography.textTransform,
                        textDecoration: typography.textDecoration,
                      },
                    },
                  } as Partial<CanvasElement>);
                }}
                onClose={() => setDecimalTypographyOpen(false)}
                hideTextTransform
              />
            )}
        </AnimatePresence>

        {/* Cascading Placeholder Popover */}
        <AnimatePresence>
          {placeholderOpen && (
            <PlaceholderPopover
              onInsert={(placeholder: string) => {
                const currentHtml = element.customHtml ?? "";
                handleUpdate({ customHtml: currentHtml + placeholder });
              }}
              onClose={() => setPlaceholderOpen(false)}
            />
          )}
        </AnimatePresence>
      </motion.div>
    </AnimatePresence>
  );
}

export default FloatingSettingsPanel;
