import httpClient from "../../utils/http-client";
import Sortable from 'sortablejs';

interface SortableDragConfig {
    selector: string;
    changePositionUrl: string;
    handle?: string;
    animation?: number;
    paginationInfo?: {
        currentPage: number;
        perPage: number;
        total?: number;
    };
    positionOrder?: 'asc' | 'desc'; // Default is 'asc' - 1, 2, 3... vs 'desc' - n, n-1, n-2...
}

interface SortableDragData {
    init(): void;
    isLoading: boolean;
    error: string | null;
    sortableInstance: Sortable | null;
    saveNewPosition(itemId: number, newIndex: number): Promise<void>;
    calculateAbsolutePosition(newIndex: number): number;
}

export function sortableDrag(config: SortableDragConfig): SortableDragData {
    return {
        isLoading: false,
        error: null,
        sortableInstance: null,

        init() {
            const container = document.querySelector(config.selector);
            if (!container) return;
            
            // Configure Sortable with our settings
            this.sortableInstance = Sortable.create(container as HTMLElement, {
                handle: config.handle || '.drag-handle',
                animation: config.animation || 150,
                ghostClass: 'bg-gray-100',
                chosenClass: 'bg-blue-100',
                dragClass: 'bg-blue-50',
                forceAutoScrollFallback: true,
                scrollSpeed: 30,
                onEnd: async (evt: Sortable.SortableEvent) => {
                    const itemEl = evt.item;
                    const dataItemId = itemEl.getAttribute('data-item-id');
                    const itemId = dataItemId ? parseInt(dataItemId, 10) : null;
                    const newIndex = evt.newIndex !== undefined ? evt.newIndex : -1;
                    
                    if (itemId && newIndex >= 0) {
                        // Calculate absolute position considering pagination
                        const absolutePosition = this.calculateAbsolutePosition(newIndex);
                        await this.saveNewPosition(itemId, absolutePosition);
                    }
                }
            });
        },

        // Calculate the absolute position considering pagination and order type
        calculateAbsolutePosition(newIndex: number): number {
            if (!config.paginationInfo) {
                return newIndex;
            }
            
            const { currentPage, perPage, total = 0 } = config.paginationInfo;
            const isDescending = config.positionOrder === 'desc';
            
            if (isDescending) {
                // For descending order (highest number first, like 100, 99, 98...)
                // We need to calculate from the end
                if (total) {
                    // If we know the total, we can calculate precisely
                    const offset = (currentPage - 1) * perPage;
                    // For desc order, we start with total and go down
                    return total - (offset + newIndex);
                } else {
                    // Without total, just return the visual index but notify it's not accurate
                    console.warn('Cannot calculate accurate absolute position in desc order without total count');
                    return newIndex;
                }
            } else {
                // For ascending order (1, 2, 3...)
                // Calculate offset based on current page (0-indexed in calculation)
                const offset = (currentPage - 1) * perPage;

                // Return absolute position in the entire collection
                return offset + newIndex + 1;
            }
        },

        async saveNewPosition(itemId: number, newPosition: number) {
            this.isLoading = true;
            this.error = null;

            const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || "";
            
            try {
                const response = await httpClient.post(config.changePositionUrl, {
                    itemId: itemId,
                    newPosition: newPosition,
                    positionOrder: config.positionOrder || 'asc' // Pass the order type to the server
                }, {
                    headers: {
                        'X-CSRF-TOKEN': csrfToken,
                        'Content-Type': 'application/json',
                        'Accept': 'application/json'
                    }
                });
                
                if (response.data.success) {
                    // Reload the page to reflect the new order
                    window.location.reload();
                } else {
                    this.error = '並び替えに失敗しました';
                    console.error('Position change failed:', response.data);
                    alert(this.error);
                }
            } catch (error) {
                this.error = '通信エラーが発生しました';
                console.error('Position change error:', error);
                alert(this.error);
            } finally {
                this.isLoading = false;
            }
        }
    };
}

// Alpine.js データオブジェクトとして登録
document.addEventListener("alpine:init", () => {
    Alpine.data("sortableDrag", sortableDrag);
});
