import { jsx, jsxs } from 'react/jsx-runtime';
import { memo, useState, useCallback, useMemo } from 'react';
import isDeepEqual from '../../../../../../../_virtual/index.mjs';
import { Button } from '../../../button.mjs';
import { ChevronDown, ChevronRight, GripVertical, Plus, MoreVertical } from 'lucide-react';
import { cn } from '../../../../lib/utils.mjs';
import { hasLayerChildren } from '../../../../lib/ui-builder/store/layer-utils.mjs';
import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem } from '../../../dropdown-menu.mjs';
import { AddComponentsPopover } from './add-component-popover.mjs';
import { NameEdit } from './name-edit.mjs';
import { useEditorStore } from '../../../../lib/ui-builder/store/editor-store.mjs';
import { hasAnyChildrenField, hasChildrenFieldOfTypeString } from '../../../../lib/ui-builder/store/schema-utils.mjs';

const TreeRowNode = memo(({
  node,
  id,
  level,
  open,
  draggable,
  onToggle,
  nodeAttributes,
  selectedLayerId,
  selectLayer,
  removeLayer,
  duplicateLayer,
  updateLayer
}) => {
  const componentRegistry = useEditorStore((state) => state.registry);
  const [isRenaming, setIsRenaming] = useState(false);
  const [popoverOrMenuOpen, setPopoverOrMenuOpen] = useState(false);
  const allowPagesCreation = useEditorStore(
    (state) => state.allowPagesCreation
  );
  const allowPagesDeletion = useEditorStore(
    (state) => state.allowPagesDeletion
  );
  const handleOpen = useCallback(() => {
    onToggle(id, !open);
  }, [id, open, onToggle]);
  const handleSelect = useCallback(() => {
    selectLayer(node.id);
  }, [node.id, selectLayer]);
  const handleRemove = useCallback(() => {
    removeLayer(node.id);
  }, [node.id, removeLayer]);
  const handleDuplicate = useCallback(() => {
    duplicateLayer(node.id);
  }, [node.id, duplicateLayer]);
  const handleRenameClick = useCallback(() => {
    setIsRenaming(true);
  }, []);
  const handleSaveRename = useCallback(
    (newName) => {
      updateLayer(node.id, {}, { name: newName });
      setIsRenaming(false);
    },
    [node.id, updateLayer]
  );
  const handleCancelRename = useCallback(() => {
    setIsRenaming(false);
  }, []);
  const canRenderAddChild = useMemo(() => {
    const componentDef = componentRegistry[node.type];
    if (!componentDef) return false;
    const canAddChildren = "shape" in componentDef.schema && hasAnyChildrenField(componentDef.schema) && !hasChildrenFieldOfTypeString(componentDef.schema);
    return canAddChildren;
  }, [node, componentRegistry]);
  const { key, ...rest } = nodeAttributes;
  if (!node) {
    return null;
  }
  return /* @__PURE__ */ jsxs("div", { ...rest, className: "w-fit flex items-center group relative", children: [
    /* @__PURE__ */ jsx(RowOffset, { level }),
    hasLayerChildren(node) && node.children.length > 0 ? /* @__PURE__ */ jsx(
      Button,
      {
        className: "w-4 ml-3 p-0",
        variant: "ghost",
        size: "sm",
        onClick: handleOpen,
        children: open ? /* @__PURE__ */ jsx(ChevronDown, { className: "size-4 bg-secondary rounded-full" }) : /* @__PURE__ */ jsx(ChevronRight, { className: "size-4 bg-secondary rounded-full" })
      }
    ) : /* @__PURE__ */ jsx("div", { className: "size-4 rounded-none opacity-0 ml-3" }),
    isRenaming ? /* @__PURE__ */ jsx(
      NameEdit,
      {
        initialName: node.name ?? "",
        onSave: handleSaveRename,
        onCancel: handleCancelRename
      }
    ) : /* @__PURE__ */ jsxs(
      Button,
      {
        variant: "ghost",
        size: "sm",
        className: cn(
          "pl-0 gap-0",
          node.id === selectedLayerId ? "text-primary" : "text-muted-foreground"
        ),
        onClick: handleSelect,
        children: [
          /* @__PURE__ */ jsx(
            "div",
            {
              className: cn(
                "w-4 h-full flex items-center justify-center cursor-move opacity-0 rounded group-hover:opacity-100 hover:bg-muted-foreground hover:text-muted transition-opacity duration-200 ease-in-out",
                popoverOrMenuOpen ? "opacity-100" : "opacity-0"
              ),
              draggable,
              children: /* @__PURE__ */ jsx(GripVertical, { className: "size-4" })
            }
          ),
          node.name
        ]
      }
    ),
    canRenderAddChild && /* @__PURE__ */ jsx(
      AddComponentsPopover,
      {
        parentLayerId: node.id,
        onOpenChange: setPopoverOrMenuOpen,
        children: /* @__PURE__ */ jsxs(
          Button,
          {
            variant: "ghost",
            size: "icon",
            className: cn(
              "opacity-0 group-hover:opacity-100 transition-opacity duration-200 ease-in-out",
              popoverOrMenuOpen ? "opacity-100" : "opacity-0"
            ),
            children: [
              /* @__PURE__ */ jsx(Plus, { className: "h-4 w-4" }),
              /* @__PURE__ */ jsx("span", { className: "sr-only", children: "Add component" })
            ]
          }
        )
      }
    ),
    /* @__PURE__ */ jsxs(DropdownMenu, { onOpenChange: setPopoverOrMenuOpen, children: [
      /* @__PURE__ */ jsx(DropdownMenuTrigger, { asChild: true, children: /* @__PURE__ */ jsx(
        Button,
        {
          className: cn(
            "opacity-0 group-hover:opacity-100 transition-opacity duration-200 ease-in-out",
            popoverOrMenuOpen ? "opacity-100" : "opacity-0"
          ),
          variant: "ghost",
          size: "icon",
          "aria-label": "More options",
          children: /* @__PURE__ */ jsx(MoreVertical, { className: "h-4 w-4" })
        }
      ) }),
      /* @__PURE__ */ jsxs(DropdownMenuContent, { align: "end", children: [
        /* @__PURE__ */ jsx(DropdownMenuItem, { onClick: handleRenameClick, children: "Rename" }),
        allowPagesCreation && /* @__PURE__ */ jsx(DropdownMenuItem, { onClick: handleDuplicate, children: "Duplicate" }),
        allowPagesDeletion && /* @__PURE__ */ jsx(DropdownMenuItem, { onClick: handleRemove, children: "Remove" })
      ] })
    ] })
  ] }, key);
}, (prevProps, nextProps) => {
  if (prevProps.node.id !== nextProps.node.id) return false;
  if (!isDeepEqual(prevProps.node, nextProps.node)) return false;
  if (prevProps.id !== nextProps.id) return false;
  if (prevProps.level !== nextProps.level) return false;
  if (prevProps.open !== nextProps.open) return false;
  if (prevProps.draggable !== nextProps.draggable) return false;
  if (prevProps.selectedLayerId !== nextProps.selectedLayerId) return false;
  if (!isDeepEqual(prevProps.nodeAttributes, nextProps.nodeAttributes)) return false;
  if (prevProps.onToggle !== nextProps.onToggle) return false;
  if (prevProps.selectLayer !== nextProps.selectLayer) return false;
  if (prevProps.removeLayer !== nextProps.removeLayer) return false;
  if (prevProps.duplicateLayer !== nextProps.duplicateLayer) return false;
  if (prevProps.updateLayer !== nextProps.updateLayer) return false;
  return true;
});
TreeRowNode.displayName = "TreeRowNode";
const RowOffset = ({ level }) => {
  const style = useMemo(() => ({
    width: level * 20
  }), [level]);
  const arr = useMemo(() => Array.from({ length: level }), [level]);
  return /* @__PURE__ */ jsx(
    "div",
    {
      className: "z-[-1] left-0 pointer-events-none absolute flex flex-row bottom-[20px] h-full",
      style,
      children: arr.map((_, index) => /* @__PURE__ */ jsx(
        "div",
        {
          className: cn(
            "w-5 h-full border-l border-dashed border-primary bg-background",
            index === level - 1 && "border-b "
          )
        },
        index
      ))
    }
  );
};
const TreeRowPlaceholder = ({ nodeAttributes }) => {
  const { key, ...rest } = nodeAttributes;
  return /* @__PURE__ */ jsx("div", { ...rest, className: "w-40 h-2", children: /* @__PURE__ */ jsx("div", { className: "size-full border-b-2 border-blue-500 border-dashed" }) }, key);
};

export { TreeRowNode, TreeRowPlaceholder };
