"use client";

/**
 * Left-sidebar sortable list of page sections. Uses @dnd-kit/sortable to
 * allow drag-and-drop reordering. Each item shows the block icon + name,
 * and clicking selects that section in the editor. A trailing "Add
 * Section" button opens the picker.
 */

import { DndContext, closestCenter, PointerSensor, useSensor, useSensors, type DragEndEvent } from "@dnd-kit/core";
import { arrayMove, SortableContext, useSortable, verticalListSortingStrategy } from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import { GripVertical, Plus, Square } from "lucide-react";
import * as Icons from "lucide-react";
import type { Section } from "@/lib/page-studio/section-registry";
import { getBlockDefinition } from "@/lib/page-studio/section-registry";

type IconMap = Record<string, React.ComponentType<{ className?: string }>>;

interface Props {
  sections: Section[];
  selectedId: string | null;
  onReorder: (next: Section[]) => void;
  onSelect: (id: string) => void;
  onOpenPicker: () => void;
}

export default function SortableSectionList({ sections, selectedId, onReorder, onSelect, onOpenPicker }: Props) {
  const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 4 } }));
  const handleDragEnd = (event: DragEndEvent) => {
    const { active, over } = event;
    if (!over || active.id === over.id) return;
    const oldIdx = sections.findIndex((s) => s.id === active.id);
    const newIdx = sections.findIndex((s) => s.id === over.id);
    if (oldIdx < 0 || newIdx < 0) return;
    onReorder(arrayMove(sections, oldIdx, newIdx));
  };

  return (
    <div className="flex flex-col h-full">
      <div className="px-4 py-3 border-b border-slate-200 flex items-center justify-between">
        <h3 className="text-[10px] font-bold uppercase tracking-widest text-slate-500">Sections</h3>
        <span className="text-[10px] text-slate-400 tabular-nums">{sections.length}</span>
      </div>

      <div className="flex-1 overflow-auto px-2 py-2 space-y-1">
        <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
          <SortableContext items={sections.map((s) => s.id)} strategy={verticalListSortingStrategy}>
            {sections.map((section) => (
              <SortableItem
                key={section.id}
                section={section}
                selected={section.id === selectedId}
                onSelect={() => onSelect(section.id)}
              />
            ))}
          </SortableContext>
        </DndContext>
        {sections.length === 0 && (
          <div className="text-center py-8 text-xs text-slate-400">No sections yet.</div>
        )}
      </div>

      <div className="px-3 py-3 border-t border-slate-200">
        <button
          onClick={onOpenPicker}
          className="w-full flex items-center justify-center gap-1.5 px-3 py-2 rounded-lg bg-brand-600 text-white text-xs font-semibold hover:bg-brand-700 transition-colors"
        >
          <Plus className="w-3.5 h-3.5" /> Add Section
        </button>
      </div>
    </div>
  );
}

function SortableItem({ section, selected, onSelect }: { section: Section; selected: boolean; onSelect: () => void }) {
  const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id: section.id });
  const def = getBlockDefinition(section.type);
  const iconMap = Icons as unknown as IconMap;
  const Icon = (def && iconMap[def.icon]) || Square;
  const style: React.CSSProperties = {
    transform: CSS.Transform.toString(transform),
    transition,
    opacity: isDragging ? 0.5 : 1,
  };
  return (
    <div
      ref={setNodeRef}
      style={style}
      onClick={onSelect}
      className={`group flex items-center gap-2 px-2.5 py-2 rounded-lg border text-left cursor-pointer transition-colors ${
        selected ? "bg-brand-50 border-brand-300 shadow-sm" : "bg-white border-slate-200 hover:border-slate-300"
      }`}
    >
      <button
        {...attributes}
        {...listeners}
        className="touch-none cursor-grab active:cursor-grabbing text-slate-300 hover:text-slate-500"
        onClick={(e) => e.stopPropagation()}
      >
        <GripVertical className="w-3.5 h-3.5" />
      </button>
      <div className={`w-6 h-6 rounded-md flex items-center justify-center shrink-0 ${selected ? "bg-brand-600 text-white" : "bg-slate-100 text-slate-500"}`}>
        <Icon className="w-3 h-3" />
      </div>
      <span className="flex-1 text-xs font-semibold text-slate-700 truncate">{def?.name ?? section.type}</span>
    </div>
  );
}
