/**
 * ElementPalette — Draggable element palette for Checkout Builder.
 *
 * @package ArraySubsPro
 */
import React, { useMemo } from "react";
import { __ } from "@wordpress/i18n";
import { useDraggable } from "@dnd-kit/core";
import { CSS } from "@dnd-kit/utilities";

const PALETTE_PREFIX = "palette:";

const CATEGORY_LABELS = {
  standard: __("Standard", "arraysubs"),
  advanced: __("Advanced", "arraysubs"),
  layout: __("Layout", "arraysubs"),
};

const DraggablePaletteItem = ({ typeKey, config }) => {
  const {
    attributes,
    listeners,
    setNodeRef,
    transform,
    transition,
    isDragging,
  } = useDraggable({
    id: `${PALETTE_PREFIX}${typeKey}`,
    data: {
      source: "palette",
      fieldType: typeKey,
      fieldLabel: config?.label || "",
    },
  });

  return (
    <button
      type="button"
      ref={setNodeRef}
      className={`arraysubs-cb-palette-item ${
        isDragging ? "arraysubs-cb-palette-item--dragging" : ""
      }`}
      style={{
        transform: CSS.Transform.toString(transform),
        transition,
      }}
      {...listeners}
      {...attributes}
    >
      <span className="arraysubs-cb-palette-item__label">
        {config?.label || typeKey}
      </span>
      <span className="arraysubs-cb-palette-item__meta">
        {CATEGORY_LABELS[config?.category] || __("Custom", "arraysubs")}
      </span>
    </button>
  );
};

const ElementPalette = ({ fieldTypes = {} }) => {
  const groupedTypes = useMemo(() => {
    return Object.entries(fieldTypes).reduce((groups, [typeKey, config]) => {
      const category = config?.category || "standard";

      if (!groups[category]) {
        groups[category] = [];
      }

      groups[category].push([typeKey, config]);

      return groups;
    }, {});
  }, [fieldTypes]);

  if (!Object.keys(groupedTypes).length) {
    return (
      <div className="arraysubs-cb-palette arraysubs-cb-palette--empty">
        <p>{__("No elements are available right now.", "arraysubs")}</p>
      </div>
    );
  }

  return (
    <div className="arraysubs-cb-palette">
      <p className="arraysubs-cb-palette__intro">
        {__(
          "Drag any element into the active step to insert it where you want.",
          "arraysubs",
        )}
      </p>

      {Object.entries(groupedTypes).map(([category, items]) => (
        <div key={category} className="arraysubs-cb-palette__group">
          <div className="arraysubs-cb-palette__group-title">
            {CATEGORY_LABELS[category] || category}
          </div>

          <div className="arraysubs-cb-palette__grid">
            {items.map(([typeKey, config]) => (
              <DraggablePaletteItem
                key={typeKey}
                typeKey={typeKey}
                config={config}
              />
            ))}
          </div>
        </div>
      ))}
    </div>
  );
};

export default ElementPalette;
