import { useState, useCallback } from 'react';
import reorderService from '../services/reorderService';

/**
 * Custom Hook für Drag-and-Drop Reordering
 * @param {Object[]} initialImages - Initiale Bilder-Array
 * @param {string} groupId - Gruppen-ID für API-Calls
 * @param {function} onSuccess - Success-Callback
 * @param {function} onError - Error-Callback
 */
export const useReordering = (initialImages = [], groupId = null, onSuccess = null, onError = null) => {
    const [images, setImages] = useState(initialImages);
    const [isReordering, setIsReordering] = useState(false);
    const [reorderError, setReorderError] = useState(null);

    /**
     * Handle drag end event from @dnd-kit
     * @param {Object} event - DnD event with active and over properties
     */
    const handleDragEnd = useCallback(async (event) => {
        const { active, over } = event;
        
        if (!over || active.id === over.id) {
            return; // No change needed
        }

        const activeIndex = images.findIndex(img => img.id === active.id);
        const overIndex = images.findIndex(img => img.id === over.id);
        
        if (activeIndex === -1 || overIndex === -1) {
            console.error('[useReordering] Invalid drag indices:', { activeIndex, overIndex });
            return;
        }

        // Optimistic update - update UI immediately
        const reorderedImages = reorderService.reorderArray(images, activeIndex, overIndex);
        setImages(reorderedImages);
        
        // Clear previous errors
        setReorderError(null);

        if (!groupId) {
            console.warn('[useReordering] No groupId provided, skipping API call');
            return;
        }

        setIsReordering(true);

        try {
            // Extract image IDs in new order
            const newImageIds = reorderedImages.map(img => img.id);
            
            // Save to backend
            const response = await reorderService.updateImageOrder(groupId, newImageIds);
            
            console.log('[useReordering] Reorder successful:', response);
            
            // Call success callback if provided
            if (onSuccess) {
                onSuccess(reorderedImages, response);
            }
            
        } catch (error) {
            console.error('[useReordering] Reorder failed:', error);
            
            // Rollback optimistic update
            setImages(images);
            setReorderError(error.message || 'Failed to save new order');
            
            // Call error callback if provided
            if (onError) {
                onError(error);
            }
        } finally {
            setIsReordering(false);
        }
    }, [images, groupId, onSuccess, onError]);

    /**
     * Reset images to initial state
     */
    const resetImages = useCallback(() => {
        setImages(initialImages);
        setReorderError(null);
    }, [initialImages]);

    /**
     * Update images from external source (e.g., props change)
     */
    const updateImages = useCallback((newImages) => {
        setImages(newImages);
        setReorderError(null);
    }, []);

    /**
     * Clear error state
     */
    const clearError = useCallback(() => {
        setReorderError(null);
    }, []);

    return {
        images,
        isReordering,
        reorderError,
        handleDragEnd,
        resetImages,
        updateImages,
        clearError
    };
};