import { useEffect, useRef, useState } from 'react';
import {
  DndContext,
  DragOverlay,
  PointerSensor,
  closestCenter,
  useSensor,
  useSensors,
  type DragStartEvent,
  type DragEndEvent,
} from '@dnd-kit/core';
import { SortableContext, horizontalListSortingStrategy, arrayMove } from '@dnd-kit/sortable';
import { toast } from 'sonner';
import { useRackStore } from '../../store/useRackStore';
import { apiClient } from '../../api/client';
import { RackToolbar } from './RackToolbar';
import { RackColumn } from './RackColumn';
import { DevicePalette } from './DevicePalette';
import { ConnectionLayer } from './ConnectionLayer';
import { AddModuleModal } from '../modals/AddModuleModal';
import { PortConfigModal } from '../modals/PortConfigModal';
import { ConnectionConfigModal } from '../modals/ConnectionConfigModal';
import { RackSkeleton } from '../ui/Skeleton';
import type { ModuleType } from '../../types';
import { MODULE_TYPE_COLORS, MODULE_TYPE_LABELS } from '../../lib/constants';
import { cn } from '../../lib/utils';

interface PendingDrop {
  rackId: string;
  uPosition: number;
  type: ModuleType;
}

interface HoverSlot {
  rackId: string;
  uPosition: number;
}

function DragOverlayItem({ type }: { type: ModuleType }) {
  const colors = MODULE_TYPE_COLORS[type];
  return (
    <div
      className={cn(
        'px-3 py-1.5 rounded border text-xs font-semibold text-white shadow-2xl opacity-90 pointer-events-none',
        colors.bg,
        colors.border
      )}
    >
      {MODULE_TYPE_LABELS[type]}
    </div>
  );
}

function ModuleDragOverlay({ label }: { label: string }) {
  return (
    <div className="px-3 py-1.5 rounded border bg-slate-600 border-slate-400 text-xs font-semibold text-white shadow-2xl opacity-90 pointer-events-none">
      {label}
    </div>
  );
}

/**
 * Resolve which rack slot (if any) is under the pointer during a drag.
 *
 * Strategy: elementFromPoint at the current pointer coordinates.
 * - All ModuleBlocks get pointer-events:none via the body.rack-dragging CSS rule,
 *   so elementFromPoint sees through them to the slot element beneath.
 * - DragOverlay has pointer-events:none natively (dnd-kit).
 * - RackSlot divs carry data-rack-id / data-u-pos attributes that we read here.
 */
function resolveSlotFromPoint(clientX: number, clientY: number): HoverSlot | null {
  const el = document.elementFromPoint(clientX, clientY);
  if (!el) return null;

  const slotEl = el.closest('[data-rack-id][data-u-pos]') as HTMLElement | null;
  if (!slotEl) return null;

  const rackId = slotEl.dataset.rackId;
  const uPos = parseInt(slotEl.dataset.uPos ?? '', 10);
  if (!rackId || isNaN(uPos)) return null;

  return { rackId, uPosition: uPos };
}

const POINTER_SENSOR_OPTIONS = {
  activationConstraint: { distance: 6 },
};

export function RackPlanner() {
  const { racks, loading, fetchRacks, moveModule, activeConfigPortId, setActiveConfigPortId, activeConfigConnectionId, setActiveConfigConnectionId } = useRackStore();
  const canvasRef = useRef<HTMLDivElement>(null);

  // Drag state
  const [activePaletteType, setActivePaletteType] = useState<ModuleType | null>(null);
  const [activeDragModuleLabel, setActiveDragModuleLabel] = useState<string | null>(null);
  const [draggingModuleId, setDraggingModuleId] = useState<string | null>(null);
  const [pendingDrop, setPendingDrop] = useState<PendingDrop | null>(null);

  // hoverSlot drives the blue highlight on slots during drag.
  // hoverSlotRef is the reliable read-path inside async handleDragEnd
  // (avoids stale-closure issues with state).
  const [hoverSlot, setHoverSlot] = useState<HoverSlot | null>(null);
  const hoverSlotRef = useRef<HoverSlot | null>(null);

  // Tracks whether ANY module/palette drag is in progress — used to
  // activate the body.rack-dragging CSS class and the pointermove listener.
  const isDraggingAnyRef = useRef(false);

  function updateHoverSlot(slot: HoverSlot | null) {
    hoverSlotRef.current = slot;
    setHoverSlot(slot);
  }

  const sensors = useSensors(
    useSensor(PointerSensor, POINTER_SENSOR_OPTIONS)
  );

  useEffect(() => {
    fetchRacks().catch(() => toast.error('Failed to load racks'));
  }, [fetchRacks]);

  /**
   * Native pointermove listener registered once on mount.
   * Only runs while isDraggingAnyRef is true — gives us the exact cursor
   * position without any reconstruction arithmetic, so resolveSlotFromPoint
   * is always called with accurate coordinates.
   */
  useEffect(() => {
    function onPointerMove(e: PointerEvent) {
      if (!isDraggingAnyRef.current) return;
      const slot = resolveSlotFromPoint(e.clientX, e.clientY);
      
      const prev = hoverSlotRef.current;
      if (prev?.rackId !== slot?.rackId || prev?.uPosition !== slot?.uPosition) {
        hoverSlotRef.current = slot;
        setHoverSlot(slot);
      }
    }

    // Capture phase so we get the event before any element can stop propagation.
    window.addEventListener('pointermove', onPointerMove, { capture: true });
    return () => window.removeEventListener('pointermove', onPointerMove, { capture: true });
  }, []);

  function handleDragStart(event: DragStartEvent) {
    const data = event.active.data.current as Record<string, unknown>;
    if (data?.dragType === 'palette') {
      setActivePaletteType(data.type as ModuleType);
      isDraggingAnyRef.current = true;
      document.body.classList.add('rack-dragging');
    } else if (data?.dragType === 'module') {
      setDraggingModuleId(data.moduleId as string);
      setActiveDragModuleLabel(data.label as string);
      isDraggingAnyRef.current = true;
      document.body.classList.add('rack-dragging');
    }
    updateHoverSlot(null);
  }

  async function handleDragEnd(event: DragEndEvent) {
    const { active, over } = event;

    // Stop native hover tracking and remove body class FIRST
    isDraggingAnyRef.current = false;
    document.body.classList.remove('rack-dragging');

    // Capture hoverSlot BEFORE resetting state
    const slot = hoverSlotRef.current;

    setActivePaletteType(null);
    setActiveDragModuleLabel(null);
    setDraggingModuleId(null);
    updateHoverSlot(null);

    const dragData = active.data.current as Record<string, unknown>;

    // --- Palette → slot: open AddModuleModal pre-filled ---
    if (dragData?.dragType === 'palette' && slot) {
      setPendingDrop({
        type: dragData.type as ModuleType,
        rackId: slot.rackId,
        uPosition: slot.uPosition,
      });
      return;
    }

    // --- Module → slot: move the module ---
    if (dragData?.dragType === 'module' && slot) {
      const moduleId = dragData.moduleId as string;

      // No-op if dropped on own position
      if (dragData.fromRackId === slot.rackId && dragData.fromUPosition === slot.uPosition) return;

      try {
        await moveModule(moduleId, slot.rackId, slot.uPosition);
        toast.success('Module moved');
      } catch (err) {
        toast.error(err instanceof Error ? err.message : 'Move failed');
      }
      return;
    }

    // --- Rack header → rack header: reorder racks ---
    if (!over) return;
    const dropData = over.data.current as Record<string, unknown> | undefined;
    if (dragData?.dragType === 'rack' && dropData?.dragType === 'rack') {
      const oldIndex = racks.findIndex((r) => r.id === active.id);
      const newIndex = racks.findIndex((r) => r.id === over.id);
      if (oldIndex === newIndex) return;

      const reordered = arrayMove(racks, oldIndex, newIndex);
      try {
        await Promise.all(
          reordered.map((rack, idx) =>
            rack.displayOrder !== idx
              ? apiClient.racks.update(rack.id, { displayOrder: idx })
              : Promise.resolve(rack)
          )
        );
        await fetchRacks();
      } catch {
        toast.error('Failed to save rack order');
        await fetchRacks();
      }
    }
  }

  const rackIds = racks.map((r) => r.id);

  return (
    <DndContext
      sensors={sensors}
      collisionDetection={closestCenter}
      onDragStart={handleDragStart}
      onDragEnd={handleDragEnd}
    >
      <div className="flex flex-col h-screen bg-[#0f1117]">
        <RackToolbar rackCanvasRef={canvasRef} />

        <div className="flex flex-1 overflow-hidden">
          <DevicePalette />

          <div className="flex-1 overflow-auto relative rack-planner-canvas">
            {loading ? (
              <RackSkeleton />
            ) : racks.length === 0 ? (
              <div className="flex flex-col items-center justify-center h-full gap-3 text-center px-4">
                <div className="w-16 h-16 bg-slate-800 rounded-xl border border-slate-700 flex items-center justify-center">
                  <svg width="32" height="32" viewBox="0 0 18 18" fill="none">
                    <rect x="1" y="2" width="16" height="3" rx="1" fill="#475569" />
                    <rect x="1" y="7" width="16" height="3" rx="1" fill="#475569" opacity="0.7" />
                    <rect x="1" y="12" width="16" height="3" rx="1" fill="#475569" opacity="0.4" />
                  </svg>
                </div>
                <div>
                  <p className="text-slate-300 font-medium">No racks yet</p>
                  <p className="text-slate-500 text-sm mt-1">
                    Click <strong className="text-slate-300">Add Rack</strong> in the toolbar to create your first rack.
                  </p>
                </div>
              </div>
            ) : (
              <>
                <SortableContext items={rackIds} strategy={horizontalListSortingStrategy}>
                  <div
                    ref={canvasRef}
                    className="flex gap-4 p-4 min-h-full items-start"
                    style={{ background: '#0f1117' }}
                  >
                    {racks.map((rack) => (
                      <RackColumn
                        key={rack.id}
                        rack={rack}
                        hoverSlot={hoverSlot}
                      />
                    ))}
                  </div>
                </SortableContext>
                <ConnectionLayer />
              </>
            )}
          </div>
        </div>
      </div>

      <DragOverlay dropAnimation={null} className="pointer-events-none" zIndex={999} style={{ pointerEvents: 'none' }}>
        {activePaletteType && <DragOverlayItem type={activePaletteType} />}
        {activeDragModuleLabel && <ModuleDragOverlay label={activeDragModuleLabel} />}
      </DragOverlay>

      {pendingDrop && (
        <AddModuleModal
          open={true}
          onClose={() => setPendingDrop(null)}
          rackId={pendingDrop.rackId}
          uPosition={pendingDrop.uPosition}
          initialType={pendingDrop.type}
        />
      )}

      {activeConfigPortId && (
        <PortConfigModal
          open={!!activeConfigPortId}
          portId={activeConfigPortId}
          onClose={() => setActiveConfigPortId(null)}
        />
      )}

      {activeConfigConnectionId && (
        <ConnectionConfigModal
          open={!!activeConfigConnectionId}
          connectionId={activeConfigConnectionId}
          onClose={() => setActiveConfigConnectionId(null)}
        />
      )}
    </DndContext>
  );
}
