import httpClient from "../../utils/http-client";

interface SortableButtonConfig {
    changePositionUrl: string;
}

interface SortableButtonData {
    isLoading: boolean;
    error: string | null;
    changePosition(direction: 'up' | 'down'): Promise<void>;
}

export function sortableButton(config: SortableButtonConfig): SortableButtonData {
    return {
        isLoading: false,
        error: null,
        
        async changePosition(direction: 'up' | 'down'): Promise<void> {
            this.isLoading = true;
            this.error = null;

            const csrfToken =
                document
                    .querySelector('meta[name="csrf-token"]')
                    ?.getAttribute("content") || "";
            
            try {
                const response = await httpClient.post(config.changePositionUrl, {
                    direction: direction
                }, {
                    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:', this.error);
                    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("sortableButton", sortableButton);
});
