/**
 * ElementToolbar Component
 *
 * Top bar containing available elements for the price layout builder.
 * Shows elements based on current scenario with plus icon on hover.
 * Disables price elements (regularPrice, salePrice) when one already exists.
 */

import { useState, useEffect } from "react";
import * as Tooltip from "@radix-ui/react-tooltip";
import { PlusIcon, CheckIcon } from "@radix-ui/react-icons";
import { motion, AnimatePresence } from "motion/react";

import type { PriceScenario } from "../../types";
import type { ElementDefinition } from "../../registry/elementRegistry";
import { getElementsForScenario } from "../../registry";
import { useHasRegularPrice, useHasSalePrice, useHasVariablePriceRange } from "../../stores/canvasStore";
import { elementIconComponents } from "../icons/ElementIcons";

interface ElementToolbarProps {
  scenario: PriceScenario;
  onAddElement: (definition: ElementDefinition) => void;
  disabled?: boolean;
}

export function ElementToolbar({ scenario, onAddElement, disabled = false }: ElementToolbarProps) {
  const [elements, setElements] = useState<ElementDefinition[]>([]);
  const [hoveredId, setHoveredId] = useState<string | null>(null);
  const hasRegularPrice = useHasRegularPrice();
  const hasSalePrice = useHasSalePrice();
  const hasVariablePriceRange = useHasVariablePriceRange();

  // Load elements for current scenario
  useEffect(() => {
    setElements(getElementsForScenario(scenario));
  }, [scenario]);

  // Check if element can be added (price elements limited to one each)
  const canAddElement = (type: string): boolean => {
    if (type === "regularPrice") return !hasRegularPrice;
    if (type === "salePrice") return !hasSalePrice;
    if (type === "variablePriceRange") return !hasVariablePriceRange;
    return true;
  };

  return (
    <Tooltip.Provider delayDuration={300}>
      <div className="element-toolbar">
        <div className="element-toolbar__header">
          <span className="element-toolbar__title">Elements</span>
        </div>

        <div className="element-toolbar__items">
          <AnimatePresence mode="popLayout">
            {elements.map((definition) => {
              const isElementDisabled = disabled || !canAddElement(definition.type);
              const alreadyExists = !canAddElement(definition.type);

              return (
                <ElementToolbarItem
                  key={definition.type}
                  definition={definition}
                  isHovered={hoveredId === definition.type}
                  onHover={(hovered) => setHoveredId(hovered ? definition.type : null)}
                  onAdd={() => onAddElement(definition)}
                  disabled={isElementDisabled}
                  alreadyExists={alreadyExists}
                />
              );
            })}
          </AnimatePresence>
        </div>

        {elements.length === 0 && <div className="element-toolbar__empty">No elements available for this scenario</div>}
      </div>
    </Tooltip.Provider>
  );
}

interface ElementToolbarItemProps {
  definition: ElementDefinition;
  isHovered: boolean;
  onHover: (hovered: boolean) => void;
  onAdd: () => void;
  disabled?: boolean;
  alreadyExists?: boolean;
}

function ElementToolbarItem({ definition, isHovered, onHover, onAdd, disabled = false, alreadyExists = false }: ElementToolbarItemProps) {
  const IconComponent = elementIconComponents[definition.icon];

  // Add data-onboarding attribute for regularPrice element
  const onboardingAttr = definition.type === "regularPrice" ? { "data-onboarding": "add-regular-price" } : {};

  return (
    <Tooltip.Root>
      <Tooltip.Trigger asChild>
        <motion.div
          className="element-toolbar-item"
          data-hovered={isHovered}
          data-disabled={disabled}
          data-exists={alreadyExists}
          {...onboardingAttr}
          onMouseEnter={() => onHover(true)}
          onMouseLeave={() => onHover(false)}
          onClick={() => !disabled && onAdd()}
          initial={{ opacity: 0, scale: 0.9 }}
          animate={{ opacity: 1, scale: 1 }}
          exit={{ opacity: 0, scale: 0.9 }}
          transition={{ duration: 0.15 }}
          style={{ cursor: disabled ? "not-allowed" : "pointer" }}
        >
          <div className="element-toolbar-item__icon">{IconComponent ? <IconComponent className="w-6 h-6" /> : null}</div>

          <span className="element-toolbar-item__label">{definition.label}</span>

          <AnimatePresence>
            {alreadyExists ? (
              <motion.span
                className="element-toolbar-item__check"
                initial={{ opacity: 0, scale: 0 }}
                animate={{ opacity: 1, scale: 1 }}
                exit={{ opacity: 0, scale: 0 }}
                transition={{ duration: 0.1 }}
                title="Already added"
              >
                <CheckIcon className="w-3.5 h-3.5 text-green-500" />
              </motion.span>
            ) : isHovered && !disabled ? (
              <motion.button
                className="element-toolbar-item__add"
                onClick={(e) => {
                  e.stopPropagation();
                  onAdd();
                }}
                initial={{ opacity: 0, scale: 0 }}
                animate={{ opacity: 1, scale: 1 }}
                exit={{ opacity: 0, scale: 0 }}
                transition={{ duration: 0.1 }}
                aria-label={`Add ${definition.label}`}
              >
                <PlusIcon className="w-3.5 h-3.5" />
              </motion.button>
            ) : null}
          </AnimatePresence>
        </motion.div>
      </Tooltip.Trigger>

      <Tooltip.Portal>
        <Tooltip.Content className="element-tooltip" sideOffset={8} side="bottom">
          <div className="element-tooltip__content">
            <span className="element-tooltip__title">{definition.label}</span>
            <span className="element-tooltip__description">
              {alreadyExists ? `${definition.label} already added to canvas` : definition.description}
            </span>
            <span className="element-tooltip__category">Category: {definition.category}</span>
          </div>
          <Tooltip.Arrow className="element-tooltip__arrow" />
        </Tooltip.Content>
      </Tooltip.Portal>
    </Tooltip.Root>
  );
}

export default ElementToolbar;
