<x-app-layout>
    <x-slot name="title">Reports</x-slot>
    <x-slot name="header">
        <div class="flex justify-between items-center">
            <h2 class="font-semibold text-xl text-gray-800 leading-tight">
                {{ __('Custom Report Builder') }}
            </h2>
            <a href="{{ route('reports.index') }}" class="px-4 py-2 bg-gray-100 text-gray-700 rounded-md hover:bg-gray-200 text-sm font-medium transition-colors">
                Cancel
            </a>
        </div>
    </x-slot>

    <div class="py-12" x-data="reportBuilder()">
        <div class="max-w-5xl mx-auto sm:px-6 lg:px-8 pb-12">
            <div class="bg-white shadow-sm sm:rounded-lg mb-12">
                <form action="{{ route('reports.store') }}" method="POST" class="p-6 border-b border-gray-200 space-y-8" @submit.prevent="submitForm">
                    @csrf
                    
                    <!-- Basic Setup -->
                    <div>
                        <h3 class="text-lg font-medium text-gray-900 border-b pb-2 mb-4">1. Basic Setup</h3>
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Report Name *</label>
                                <input type="text" x-model="formData.name" required class="block w-full border-gray-300 rounded-md shadow-sm focus:ring-primary-500 focus:border-primary-500 sm:text-sm" placeholder="e.g. Sales Q3 Report">
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Data Source Module *</label>
                                <select x-model="formData.module" @change="moduleChanged" required class="block w-full border-gray-300 rounded-md shadow-sm focus:ring-primary-500 focus:border-primary-500 sm:text-sm bg-white">
                                    <option value="">Select a Module</option>
                                    @foreach($modules as $key => $label)
                                        <option value="{{ $key }}">{{ $label }}</option>
                                    @endforeach
                                </select>
                            </div>
                        </div>
                    </div>

                    <!-- Columns Selection (Drag & Drop) -->
                    <div x-show="formData.module">
                        <h3 class="text-lg font-medium text-gray-900 border-b pb-2 mb-4">2. Select & Order Columns</h3>
                        <p class="text-sm text-gray-500 mb-4">Check to include, and drag to reorder the columns.</p>
                        
                        <div id="sortable-columns" class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-3 bg-gray-50 p-4 rounded-lg border border-gray-200">
                            <template x-for="(colData, index) in columnList" :key="colData.key">
                                <div class="flex items-center p-3 bg-white border border-gray-200 rounded shadow-sm cursor-move sortable-item" :data-key="colData.key">
                                    <svg class="w-5 h-5 text-gray-400 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16"></path></svg>
                                    <label class="flex-1 inline-flex items-center cursor-pointer mb-0">
                                        <input type="checkbox" :value="colData.key" x-model="formData.selected_columns" class="rounded border-gray-300 text-primary-600 shadow-sm focus:border-primary-300 focus:ring focus:ring-primary-200 focus:ring-opacity-50">
                                        <span class="ml-2 text-sm text-gray-700" x-text="colData.label"></span>
                                    </label>
                                </div>
                            </template>
                        </div>
                    </div>
                    
                    <!-- Filters -->
                    <div x-show="formData.module">
                        <h3 class="text-lg font-medium text-gray-900 border-b pb-2 mb-4">3. Presentation & Filters</h3>
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Display Format</label>
                                <select x-model="formData.chart_type" class="block w-full border-gray-300 rounded-md shadow-sm focus:ring-primary-500 focus:border-primary-500 sm:text-sm bg-white">
                                    <option value="table">Data Table</option>
                                    <option value="bar">Bar Chart</option>
                                    <option value="pie">Pie Chart</option>
                                </select>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Quick Filter</label>
                                <template x-if="formData.module === 'leads'">
                                    <select x-model="formData.filters.status" class="block w-full border-gray-300 rounded-md shadow-sm focus:ring-primary-500 focus:border-primary-500 sm:text-sm bg-white">
                                        <option value="">All Statuses</option>
                                        <option value="New">New</option>
                                        <option value="Contacted">Contacted</option>
                                        <option value="Qualified">Qualified</option>
                                        <option value="Converted">Converted</option>
                                        <option value="Lost">Lost</option>
                                    </select>
                                </template>
                                <template x-if="formData.module === 'properties'">
                                    <select x-model="formData.filters.status" class="block w-full border-gray-300 rounded-md shadow-sm focus:ring-primary-500 focus:border-primary-500 sm:text-sm bg-white">
                                        <option value="">All Statuses</option>
                                        <option value="Available">Available</option>
                                        <option value="Reserved">Reserved</option>
                                        <option value="Sold">Sold</option>
                                    </select>
                                </template>
                                <template x-if="formData.module === 'invoices'">
                                    <select x-model="formData.filters.status" class="block w-full border-gray-300 rounded-md shadow-sm focus:ring-primary-500 focus:border-primary-500 sm:text-sm bg-white">
                                        <option value="">All Statuses</option>
                                        <option value="Paid">Paid</option>
                                        <option value="Unpaid">Unpaid</option>
                                        <option value="Overdue">Overdue</option>
                                    </select>
                                </template>
                                <template x-if="formData.module === 'customers'">
                                    <select x-model="formData.filters.type" class="block w-full border-gray-300 rounded-md shadow-sm focus:ring-primary-500 focus:border-primary-500 sm:text-sm bg-white">
                                        <option value="">All Customers</option>
                                    </select>
                                </template>
                            </div>
                        </div>
                    </div>

                    <div class="flex justify-end pt-4" x-show="formData.module">
                        <button type="submit" class="inline-flex items-center px-4 py-2 bg-primary-600 border border-transparent rounded-md font-medium text-white shadow-sm hover:bg-primary-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500 text-sm">
                            <svg class="h-4 w-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7H5a2 2 0 00-2 2v9a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-3m-1 4l-3 3m0 0l-3-3m3 3V4"></path></svg>
                            Generate & Save Report
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    @push('scripts')
    <!-- Include SortableJS -->
    <script src="https://cdn.jsdelivr.net/npm/sortablejs@latest/Sortable.min.js"></script>
    <script>
        function reportBuilder() {
            const allColumns = @json($moduleColumns);
            
            return {
                formData: {
                    name: '',
                    module: '',
                    selected_columns: [],
                    chart_type: 'table',
                    filters: {},
                    _token: '{{ csrf_token() }}'
                },
                columnList: [],
                sortableInstance: null,
                
                moduleChanged() {
                    this.formData.selected_columns = [];
                    this.columnList = [];
                    
                    if (this.formData.module) {
                        const cols = allColumns[this.formData.module];
                        
                        Object.keys(cols).forEach(k => {
                            this.columnList.push({ key: k, label: cols[k] });
                        });
                        
                        // Auto-select all by default
                        this.formData.selected_columns = this.columnList.map(c => c.key);
                        
                        this.$nextTick(() => {
                            this.initSortable();
                        });
                    }
                },
                
                initSortable() {
                    const el = document.getElementById('sortable-columns');
                    if(this.sortableInstance) {
                        this.sortableInstance.destroy();
                    }
                    this.sortableInstance = new Sortable(el, {
                        animation: 150,
                        ghostClass: 'bg-blue-50',
                        onEnd: (evt) => {
                            // Update the order based on DOM changes
                            const items = el.querySelectorAll('.sortable-item');
                            const orderedKeys = Array.from(items).map(i => i.dataset.key);
                            
                            // Keep formData.selected_columns ordered according to DOM
                            // Filter it to only include checked items
                            const newSelected = [];
                            orderedKeys.forEach(k => {
                                if (this.formData.selected_columns.includes(k)) {
                                    newSelected.push(k);
                                }
                            });
                            
                            this.formData.selected_columns = newSelected;
                        }
                    });
                },
                
                async submitForm() {
                    if (this.formData.selected_columns.length === 0) {
                        alert("Please select at least one column.");
                        return;
                    }
                    
                    try {
                        const response = await fetch('{{ route('reports.store') }}', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'Accept': 'application/json',
                                'X-CSRF-TOKEN': this.formData._token
                            },
                            body: JSON.stringify(this.formData)
                        });
                        
                        const data = await response.json();
                        
                        if (data.success) {
                            window.location.href = '/reports/' + data.report_id;
                        } else {
                            alert("Failed to save report.");
                        }
                    } catch (error) {
                        console.error(error);
                        alert("An error occurred while saving.");
                    }
                }
            }
        }
    </script>
    @endpush
</x-app-layout>
