/**
 * SectionContainer — Renders a section element with column layout in the builder.
 *
 * Each column is a droppable/sortable area that accepts fields.
 *
 * @package ArraySubsPro
 */
import React from "react";
import { __ } from "@wordpress/i18n";
import { useDroppable } from "@dnd-kit/core";
import {
  SortableContext,
  useSortable,
  verticalListSortingStrategy,
} from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import { GripVertical, Pencil, Trash2, Columns3 } from "lucide-react";

export const SEC_COL_PREFIX = "sec-col::";
export const COL_ITEM_PREFIX = "col-item::";

export const isColItemId = (id) => String(id).startsWith(COL_ITEM_PREFIX);
export const isSecColId = (id) => String(id).startsWith(SEC_COL_PREFIX);

export const parseColItemId = (id) => {
  const parts = String(id).split("::");
  return {
    sectionKey: parts[1],
    colIndex: parseInt(parts[2], 10),
    fieldKey: parts[3],
  };
};

export const parseSecColId = (id) => {
  const parts = String(id).split("::");
  return { sectionKey: parts[1], colIndex: parseInt(parts[2], 10) };
};

/* ── Column item (sortable) ─────────────────────────────── */

const SortableColumnItem = ({
  field,
  sectionKey,
  colIndex,
  onEdit,
  onRemove,
}) => {
  const itemId = `${COL_ITEM_PREFIX}${sectionKey}::${colIndex}::${field.key}`;
  const {
    attributes,
    listeners,
    setNodeRef,
    transform,
    transition,
    isDragging,
  } = useSortable({ id: itemId });

  return (
    <div
      ref={setNodeRef}
      className={`arraysubs-cb-col-item${
        isDragging ? " arraysubs-cb-col-item--dragging" : ""
      }`}
      style={{ transform: CSS.Transform.toString(transform), transition }}
    >
      <div
        className="arraysubs-cb-col-item__drag"
        {...attributes}
        {...listeners}
      >
        <GripVertical size={12} />
      </div>
      <span className="arraysubs-cb-col-item__label">
        {field.label || field.key}
      </span>
      <div className="arraysubs-cb-col-item__actions">
        <button
          type="button"
          className="arraysubs-cb-col-item__btn"
          onClick={() =>
            onEdit(field, { location: "section-column", sectionKey, colIndex })
          }
          title={__("Edit", "arraysubs")}
        >
          <Pencil size={12} />
        </button>
        <button
          type="button"
          className="arraysubs-cb-col-item__btn arraysubs-cb-col-item__btn--delete"
          onClick={() =>
            onRemove(field.key, {
              location: "section-column",
              sectionKey,
              colIndex,
            })
          }
          title={__("Remove", "arraysubs")}
        >
          <Trash2 size={12} />
        </button>
      </div>
    </div>
  );
};

/* ── Single column (droppable + sortable) ───────────────── */

const SectionColumn = ({
  sectionKey,
  colIndex,
  totalCols,
  fields,
  stepId,
  onFieldEdit,
  onFieldRemove,
}) => {
  const droppableId = `${SEC_COL_PREFIX}${sectionKey}::${colIndex}`;
  const { setNodeRef, isOver } = useDroppable({ id: droppableId });

  const itemIds = fields.map(
    (f) => `${COL_ITEM_PREFIX}${sectionKey}::${colIndex}::${f.key}`,
  );

  return (
    <SortableContext items={itemIds} strategy={verticalListSortingStrategy}>
      <div
        ref={setNodeRef}
        className={`arraysubs-cb-section-col${
          isOver ? " arraysubs-cb-section-col--over" : ""
        }`}
      >
        <span className="arraysubs-cb-section-col__label">
          {totalCols > 1 ? `${__("Column", "arraysubs")} ${colIndex + 1}` : ""}
        </span>

        {fields.map((field) => (
          <SortableColumnItem
            key={field.key}
            field={field}
            sectionKey={sectionKey}
            colIndex={colIndex}
            onEdit={(item, ctx) => onFieldEdit(item, { ...ctx, stepId })}
            onRemove={(fieldKey, ctx) =>
              onFieldRemove(fieldKey, { ...ctx, stepId })
            }
          />
        ))}

        {fields.length === 0 && (
          <p className="arraysubs-cb-section-col__empty">
            {__("Drop element here", "arraysubs")}
          </p>
        )}
      </div>
    </SortableContext>
  );
};

/* ── Section container (top-level sortable) ─────────────── */

const SectionContainer = ({
  section,
  stepId,
  onEdit,
  onRemove,
  onFieldEdit,
  onFieldRemove,
  innerRef,
  draggableProps = {},
  dragHandleProps = {},
}) => {
  const columns = section.columns || 1;
  const children = section.children || [[]];

  return (
    <div
      ref={innerRef}
      className="arraysubs-cb-section-container"
      {...draggableProps}
    >
      <div className="arraysubs-cb-section-container__header">
        <div
          className="arraysubs-cb-section-container__drag"
          {...dragHandleProps}
        >
          <GripVertical size={14} />
        </div>

        <Columns3 size={14} className="arraysubs-cb-section-container__icon" />
        <span className="arraysubs-cb-section-container__label">
          {section.label || __("Section", "arraysubs")}
        </span>
        <span className="arraysubs-cb-section-container__meta">
          {columns}{" "}
          {columns === 1 ? __("col", "arraysubs") : __("cols", "arraysubs")}
        </span>

        <div className="arraysubs-cb-section-container__actions">
          <button
            type="button"
            className="arraysubs-cb-section-container__btn"
            onClick={() => onEdit(section, { location: "top-level", stepId })}
            title={__("Edit Section", "arraysubs")}
          >
            <Pencil size={12} />
          </button>
          <button
            type="button"
            className="arraysubs-cb-section-container__btn arraysubs-cb-section-container__btn--delete"
            onClick={() =>
              onRemove(section.key, { location: "top-level", stepId })
            }
            title={__("Remove Section", "arraysubs")}
          >
            <Trash2 size={12} />
          </button>
        </div>
      </div>

      <div
        className="arraysubs-cb-section-container__columns"
        style={{ gridTemplateColumns: `repeat(${columns}, 1fr)` }}
      >
        {Array.from({ length: columns }, (_, colIdx) => (
          <SectionColumn
            key={`${section.key}-col-${colIdx}`}
            sectionKey={section.key}
            colIndex={colIdx}
            totalCols={columns}
            fields={children[colIdx] || []}
            stepId={stepId}
            onFieldEdit={onFieldEdit}
            onFieldRemove={onFieldRemove}
          />
        ))}
      </div>
    </div>
  );
};

export default SectionContainer;
