import React, { useState } from "react";
import { PTW_SECTION_SKIP_ADMIN_UI_ENABLED } from "../../../config/ptwFeatures.js";

function moveItem(list, fromIndex, toIndex) {
  if (
    fromIndex === toIndex ||
    fromIndex < 0 ||
    toIndex < 0 ||
    fromIndex >= list.length ||
    toIndex >= list.length
  ) {
    return list;
  }
  const next = [...list];
  const [item] = next.splice(fromIndex, 1);
  next.splice(toIndex, 0, item);
  return next;
}

export default function SectionReorderList({
  sections = [],
  onSectionsChange,
  disabled = false,
  skipableDraft = {},
  onSkipableChange,
  onSaveSkipable,
  onRemove,
  saving = false
}) {
  const [dragIndex, setDragIndex] = useState(null);
  const [dragOverIndex, setDragOverIndex] = useState(null);

  function handleDragStart(index) {
    if (disabled || saving) return;
    setDragIndex(index);
  }

  function handleDragOver(e, index) {
    e.preventDefault();
    if (disabled || saving || dragIndex == null) return;
    setDragOverIndex(index);
  }

  function handleDrop(index) {
    if (disabled || saving || dragIndex == null) return;
    onSectionsChange?.(moveItem(sections, dragIndex, index));
    setDragIndex(null);
    setDragOverIndex(null);
  }

  function handleDragEnd() {
    setDragIndex(null);
    setDragOverIndex(null);
  }

  function moveUp(index) {
    if (disabled || saving || index <= 0) return;
    onSectionsChange?.(moveItem(sections, index, index - 1));
  }

  function moveDown(index) {
    if (disabled || saving || index >= sections.length - 1) return;
    onSectionsChange?.(moveItem(sections, index, index + 1));
  }

  if (!sections.length) {
    return (
      <p className="ptw-muted ptw-section-reorder-list__empty">
        No sections mapped to this form yet. Add one above.
      </p>
    );
  }

  return (
    <ul className="ptw-section-reorder-list" aria-label="Form sections in display order">
      {sections.map((section, index) => {
        const sid = section.section_id;
        const isDragging = dragIndex === index;
        const isDragOver = dragOverIndex === index && dragIndex !== index;

        return (
          <li
            key={sid}
            className={`ptw-section-reorder-list__item${
              isDragging ? " ptw-section-reorder-list__item--dragging" : ""
            }${isDragOver ? " ptw-section-reorder-list__item--drag-over" : ""}`}
            onDragOver={(e) => handleDragOver(e, index)}
            onDrop={() => handleDrop(index)}
          >
            <span className="ptw-section-reorder-list__position" aria-hidden="true">
              {index + 1}
            </span>

            <button
              type="button"
              className="ptw-section-reorder-list__handle"
              draggable={!disabled && !saving}
              disabled={disabled || saving}
              aria-label={`Drag section ${index + 1} to reorder`}
              title="Drag to reorder"
              onDragStart={() => handleDragStart(index)}
              onDragEnd={handleDragEnd}
            >
              ⋮⋮
            </button>

            <div className="ptw-section-reorder-list__info">
              <span className="ptw-section-reorder-list__id">#{sid}</span>
              <span className="ptw-section-reorder-list__title">
                {section.title || "Untitled"}
              </span>
            </div>

            <div className="ptw-section-reorder-list__move">
              <button
                type="button"
                className="ptw-section-reorder-list__move-btn"
                disabled={disabled || saving || index === 0}
                onClick={() => moveUp(index)}
                aria-label={`Move section ${index + 1} up`}
                title="Move up"
              >
                ↑
              </button>
              <button
                type="button"
                className="ptw-section-reorder-list__move-btn"
                disabled={disabled || saving || index === sections.length - 1}
                onClick={() => moveDown(index)}
                aria-label={`Move section ${index + 1} down`}
                title="Move down"
              >
                ↓
              </button>
            </div>

            {PTW_SECTION_SKIP_ADMIN_UI_ENABLED ? (
              <>
                <label className="ptw-map-skipable ptw-section-reorder-list__skipable">
                  <input
                    type="checkbox"
                    checked={Boolean(skipableDraft[sid])}
                    onChange={(e) => onSkipableChange?.(sid, e.target.checked)}
                    disabled={disabled || saving}
                  />
                  <span>Allow skip</span>
                </label>

                <button
                  type="button"
                  className="ptw-mgmt-btn ptw-mgmt-btn--view ptw-section-reorder-list__save-skip"
                  disabled={disabled || saving}
                  onClick={() => onSaveSkipable?.(sid)}
                >
                  Save
                </button>
              </>
            ) : null}

            <button
              type="button"
              className="ptw-mgmt-btn ptw-mgmt-btn--edit ptw-section-reorder-list__remove"
              disabled={disabled || saving}
              onClick={() => onRemove?.(sid)}
            >
              Remove
            </button>
          </li>
        );
      })}
    </ul>
  );
}
