// app/components/admin/page-builder/providers/DndProvider.tsx
'use client';
import {
  DndContext,
  PointerSensor,
  useSensor,
  useSensors,
  DragEndEvent,
  DragStartEvent,
  DragOverlay,
} from '@dnd-kit/core';
import { SortableContext, verticalListSortingStrategy } from '@dnd-kit/sortable';
import React, { useState } from 'react';
import { ComponentType } from '@/lib/page-builder/types';

interface DndProviderProps {
  children: React.ReactNode;
  items: string[];
  onComponentDrop?: (type: ComponentType) => void;
  /** Palette item dropped onto a full-width / sidebar container drop zone */
  onComponentDropIntoContainer?: (type: ComponentType, containerId: string) => void;
  /** Palette item dropped directly into a specific column of a multi-column container */
  onComponentDropIntoColumn?: (type: ComponentType, containerId: string, columnIndex: number) => void;
  onReorder?: (activeId: string, overId: string) => void;
}

export function DndProvider({
  children,
  items,
  onComponentDrop,
  onComponentDropIntoContainer,
  onComponentDropIntoColumn,
  onReorder,
}: DndProviderProps) {
  const [activeId, setActiveId]     = useState<string | null>(null);
  const [activeType, setActiveType] = useState<string | null>(null);

  const sensors = useSensors(
    useSensor(PointerSensor, { activationConstraint: { distance: 5 } })
  );

  const handleDragStart = (event: DragStartEvent) => {
    setActiveId(event.active.id as string);
    setActiveType(event.active.data.current?.type ?? null);
  };

  const handleDragEnd = (event: DragEndEvent) => {
    const { active, over } = event;
    setActiveId(null);
    setActiveType(null);

    // ── Palette item dropped somewhere ───────────────────────────────────────
    if (active.data.current?.from === 'palette') {
      const componentType = active.data.current?.type as ComponentType;
      const overId = over?.id ? String(over.id) : '';

      // Case 1: dropped into a specific column of a multi-column layout
      // id format: "column-drop-{containerId}-{columnIndex}"
      if (overId.startsWith('column-drop-')) {
        const withoutPrefix = overId.slice('column-drop-'.length);
        // columnIndex is always the last segment; containerId may contain hyphens
        const lastDash      = withoutPrefix.lastIndexOf('-');
        const containerId   = withoutPrefix.slice(0, lastDash);
        const columnIndex   = parseInt(withoutPrefix.slice(lastDash + 1), 10);
        if (containerId && !isNaN(columnIndex)) {
          onComponentDropIntoColumn?.(componentType, containerId, columnIndex);
          return;
        }
      }

      // Case 2: dropped into a full-width / sidebar container drop zone
      // id format: "container-drop-{containerId}"
      if (overId.startsWith('container-drop-')) {
        const containerId = overId.replace('container-drop-', '');
        onComponentDropIntoContainer?.(componentType, containerId);
        return;
      }

      // Case 3: dropped onto the main page canvas
      onComponentDrop?.(componentType);
      return;
    }

    // ── Reordering top-level containers ──────────────────────────────────────
    if (over && active.id !== over.id) {
      onReorder?.(active.id as string, over.id as string);
    }
  };

  return (
    <DndContext
      sensors={sensors}
      onDragStart={handleDragStart}
      onDragEnd={handleDragEnd}
    >
      <SortableContext items={items} strategy={verticalListSortingStrategy}>
        {children}
      </SortableContext>

      <DragOverlay>
        {activeId && activeType ? (
          <div className="bg-blue-50 border-2 border-blue-300 rounded-lg px-4 py-3 shadow-xl opacity-90 text-sm font-medium text-blue-700">
            + {activeType}
          </div>
        ) : null}
      </DragOverlay>
    </DndContext>
  );
}