import {
  DragEndEvent,
  DragStartEvent,
  KeyboardSensor,
  PointerSensor,
  TouchSensor,
  useSensor,
  useSensors,
} from '@dnd-kit/core';
import {
  sortableKeyboardCoordinates,
} from '@dnd-kit/sortable';
import { useCallback, useState } from 'react';
import { triggerHapticFeedback } from '@/utils/haptics';
import { useTripStore, useActiveDay } from '@/store/useTripStore';

/**
 * Sürükle-bırak (Drag and Drop) yönetimi için kullanılan hook
 */
export const useTripDragDrop = () => {
  const [activeId, setActiveId] = useState<string | null>(null);
  const reorderPlaces = useTripStore(state => state.reorderPlaces);
  const activeDay = useActiveDay();
  const activeDayPlaces = activeDay?.places || [];
  const activeDayId = useTripStore(state => state.activeDayId);

  const sensors = useSensors(
    useSensor(PointerSensor, {
      activationConstraint: {
        distance: 8,
      },
    }),
    useSensor(TouchSensor, {
      activationConstraint: {
        delay: 250,
        tolerance: 5,
      },
    }),
    useSensor(KeyboardSensor, {
      coordinateGetter: sortableKeyboardCoordinates,
    })
  );

  const handleDragStart = useCallback((event: DragStartEvent) => {
    setActiveId(event.active.id as string);
    triggerHapticFeedback('selection');
  }, []);

  const handleDragEnd = useCallback(async (event: DragEndEvent) => {
    const { active, over } = event;
    setActiveId(null);

    if (over && active.id !== over.id && activeDayId) {
      const oldIndex = activeDayPlaces.findIndex((p) => (p.tripPlaceId || p.id) === active.id);
      const newIndex = activeDayPlaces.findIndex((p) => (p.tripPlaceId || p.id) === over.id);

      if (oldIndex !== -1 && newIndex !== -1) {
        const places = [...activeDayPlaces];
        const movedItem = places.splice(oldIndex, 1)[0];
        places.splice(newIndex, 0, movedItem);
        
        await reorderPlaces(activeDayId, places);
      }
    }
  }, [activeDayId, activeDayPlaces, reorderPlaces]);

  return {
    activeId,
    sensors,
    handleDragStart,
    handleDragEnd,
  };
};
