<div class="container mx-auto">
    <x-dashboard.breadcrumb :items="[
        'Dashboard' => route('home'),
        'Ventes' => route('sales.index'),
        $sale->sale_number => route('sales.show', $sale),
        'Modifier' => null,
    ]" />

    <div class="flex gap-6 mt-6">
        <!-- Main Content -->
        <div class="w-full lg:w-8/12 space-y-6">
            <div class="space-y-6">
                <!-- Products Section -->
                <x-basics.card title="Articles de vente" subtitle="Gérez les articles de cette vente">
                    <x-slot name="action">
                        <x-basics.flash :model="'success'" :timeout="3000" />
                    </x-slot>

                    @if (session('sale_items') && count(session('sale_items')) > 0)
                        <div class="overflow-x-auto mb-6">
                            <table class="min-w-full divide-y divide-gray-200">
                                <thead
                                    class="bg-gray-50 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider">
                                    <tr>
                                        <th class="px-3 py-2">Produit</th>
                                        <th class="px-3 py-2">Quantité</th>
                                        <th class="px-3 py-2">Prix unitaire</th>
                                        <th class="px-3 py-2">Prix total</th>
                                        <th class="px-3 py-2"></th>
                                    </tr>
                                </thead>
                                <tbody class="divide-y divide-gray-100 text-sm text-gray-700">
                                    @foreach (session('sale_items', []) as $index => $item)
                                        <tr>
                                            <td class="px-3 py-2 font-medium">
                                                {{ \App\Models\Product::find($item['product_id'])->name ?? 'Produit supprimé' }}
                                            </td>
                                            <td class="px-3 py-2">{{ $item['quantity'] }}</td>
                                            <td class="px-3 py-2">
                                                {{ number_format($item['unit_price'], 0, ',', ' ') }}
                                                {{ \App\Models\Setting::DEFAULT_CURRENCY }}
                                            </td>
                                            <td class="px-3 py-2 font-medium">
                                                {{ number_format($item['total_price'], 0, ',', ' ') }}
                                                {{ \App\Models\Setting::DEFAULT_CURRENCY }}
                                            </td>
                                            <td class="px-3 py-2 text-right">
                                                <x-basics.button variant="outline-red"
                                                    wire:click="deleteSessionItem({{ $index }})" size="xs">
                                                    <i class="ph ph-bold ph-trash"></i>
                                                </x-basics.button>
                                            </td>
                                        </tr>
                                    @endforeach
                                </tbody>
                            </table>
                        </div>

                        <div class="mb-6 p-4 bg-gray-50 rounded-lg">
                            <div class="flex justify-between items-center">
                                <span class="text-lg font-medium">Total de la vente:</span>
                                <span class="text-2xl font-bold text-indigo-600">
                                    {{ number_format($total, 0, ',', ' ') }}
                                    {{ \App\Models\Setting::DEFAULT_CURRENCY }}
                                </span>
                            </div>
                        </div>
                    @else
                        <div class="text-center py-8 text-gray-500">
                            <i class="ph ph-shopping-cart text-4xl mb-2"></i>
                            <p>Aucun article ajouté à cette vente.</p>
                            <p class="text-sm">Utilisez le composant d'ajout d'articles ci-dessous pour commencer.</p>
                        </div>
                    @endif

                    <!-- Add Product Form -->
                    <form wire:submit.prevent="addProduct" x-data="{}">
                        <div class="flex items-end gap-2 bg-gray-50 p-4 rounded-lg mt-6">
                            <div class="w-2/3">
                                <x-basics.input-select name="product_id" wire:model="product_id" label="Produit"
                                    :options="$product_options" optionValue="id" optionLabel="display_name" displayLabel="name"
                                    placeholder="Sélectionner un produit"
                                    searchPlaceholder="Rechercher par nom, nom générique ou catégorie..." required
                                    mb="mb-0" />
                            </div>

                            <div>
                                <x-basics.input type="number" name="quantity" wire:model.defer="quantity"
                                    label="Quantité" min="1" step="1" required mb="mb-0" />
                            </div>

                            <div>
                                <x-basics.input type="number" name="unit_price" wire:model.defer="unit_price"
                                    label="Prix unitaire ({{ \App\Models\Setting::DEFAULT_CURRENCY }})" step="0.01"
                                    required min="0" mb="mb-0" />
                            </div>

                            <div class="flex justify-end gap-2">
                                <x-basics.button type="submit" :disabled="$product_loading || !$product_id" variant="primary">
                                    <i class="ph ph-plus"></i>
                                </x-basics.button>
                            </div>
                        </div>

                        <x-basics.flash :model="'product_error'" variant="error" :message="$product_error_message" :timeout="3000" />

                        {{-- Stock and price info --}}
                        @if ($product_id)
                            <div
                                class="mt-3 p-3 rounded-lg {{ $this->getStockStatusClasses($product_id, $quantity) }}">
                                <div class="grid grid-cols-1 md:grid-cols-3 gap-4 text-sm">
                                    <div>
                                        <span class="font-medium text-gray-600">Stock disponible:</span>
                                        <span class="ml-2 font-semibold text-gray-900">
                                            {{ $this->getProductStock($product_id) }}
                                        </span>
                                    </div>

                                    <div>
                                        <span class="font-medium text-gray-600">Unité:</span>
                                        <span class="ml-2 font-semibold text-gray-900">
                                            {{ $this->getProductUnitName($product_id) }}
                                        </span>
                                    </div>

                                    <div>
                                        <span class="font-medium text-gray-600">Prix suggéré:</span>
                                        <span class="ml-2 font-semibold text-gray-900">
                                            {{ number_format($this->getProductSellingPrice($product_id), 0, ',', ' ') }}
                                            FC
                                        </span>
                                    </div>
                                </div>
                            </div>
                        @endif
                    </form>
                </x-basics.card>

                <!-- Customer and Payment Information -->
                <x-basics.card title="Informations de la vente"
                    subtitle="Remplissez les informations de base de la vente">
                    <div>
                        <!-- Customer Selection -->
                        <x-basics.input-select name="customer_id" label="Client (optionnel)"
                            placeholder="Sélectionner un client" :options="$this->customer_options" wire:model="customer_id"
                            optionLabel="name" displayLabel="name"
                            searchPlaceholder="Rechercher par nom ou téléphone..."
                            error="{{ $errors->first('customer_id') }}" mb="mb-6" />
                    </div>

                    <div class="grid grid-cols-1 gap-6 lg:grid-cols-2 mb-6">
                        <!-- Payment Method -->
                        <div>
                            <x-basics.select name="payment_method_id" label="Méthode de paiement"
                                placeholder="Sélectionner une méthode" :options="$this->payment_method_options" wire:model="payment_method_id"
                                required mb="mb-0" />
                        </div>

                        <!-- Sale Type -->
                        <div>
                            <x-basics.select name="sale_type_id" label="Type de vente"
                                placeholder="Sélectionner un type" :options="$this->sale_type_options" wire:model="sale_type_id"
                                mb="mb-0" />
                        </div>
                    </div>

                    <!-- Notes -->
                    <x-basics.textarea name="notes" label="Notes (optionnel)" placeholder="Ajouter des remarques..."
                        rows="2" wire:model="notes" mb="mb-0" />
                </x-basics.card>

                <!-- Summary Section -->
                <x-basics.card title="Résumé de la vente" subtitle="Calculs automatiques">

                    <x-slot name="action">
                        <x-basics.flash model="success" :message="$successMessage" variant="success" :timeout="3000" />
                        <x-basics.flash model="error" :message="$errorMessage" variant="error" :timeout="5000" />
                    </x-slot>


                    @if (session('sale_items'))
                        <div class="mb-4 p-3 bg-blue-50 rounded-lg">
                            <div class="flex justify-between items-center">
                                <span class="text-sm text-blue-700">
                                    <i class="ph ph-shopping-cart mr-2"></i>
                                    {{ count(session('sale_items')) }}
                                    {{ Str::plural('article', count(session('sale_items'))) }}
                                    {{ Str::plural('ajouté', count(session('sale_items'))) }}
                                </span>
                                <x-basics.button type="button" variant="outline" wire:click="clearSaleItems">
                                    <i class="ph ph-trash mr-2"></i>
                                    Vider la liste
                                </x-basics.button>
                            </div>
                        </div>
                    @endif

                    <div class="space-y-3">
                        <div class="flex justify-between items-center">
                            <span class="text-base font-medium text-gray-700">Sous-total:</span>
                            <span
                                class="text-base font-semibold text-gray-900">{{ number_format($subtotal, 0, ',', ' ') }}
                                FC</span>
                        </div>
                        <div class="flex justify-between items-center">
                            <span class="text-base font-medium text-gray-700">Taxes:</span>
                            <span class="text-base font-semibold text-gray-900">0 FC</span>
                        </div>
                        <div class="flex justify-between items-center">
                            <span class="text-base font-medium text-gray-700">Remise:</span>
                            <span class="text-base font-semibold text-gray-900">0 FC</span>
                        </div>
                        <div class="border-t pt-3">
                            <div class="flex justify-between items-center">
                                <span class="text-xl font-bold text-gray-900">Total:</span>
                                <span class="text-xl font-bold text-blue-600">{{ number_format($total, 0, ',', ' ') }}
                                    FC</span>
                            </div>
                        </div>
                    </div>



                    @slot('footer')
                        <div class="flex justify-end gap-3">
                            <x-basics.button-link href="{{ route('sales.show', $sale) }}" variant="outline">
                                Annuler
                            </x-basics.button-link>
                            <x-basics.button type="button" variant="primary" leftIcon="check-circle"
                                wire:click="updateSale" :disabled="$loading" class="w-full">
                                @if ($loading)
                                    Modification en cours...
                                @else
                                    Enregistrer les modifications
                                @endif
                            </x-basics.button>
                        </div>
                    @endslot
                </x-basics.card>
            </div>
        </div>

        <!-- Sidebar -->
        <div class="w-full lg:w-4/12 space-y-6">
            <x-dashboard.sales.sidebar />
        </div>
    </div>
</div>