@props([
    'expense' => null,
    'expenseTypes' => [],
    'suppliers' => []
])

@php
    $isEdit = !is_null($expense);
    $action = $isEdit 
        ? route('provider.expenses.update', $expense->uuid)
        : route('provider.expenses.store');
    $method = $isEdit ? 'PUT' : 'POST';
    $title = $isEdit ? 'Modifier la dépense' : 'Informations de la dépense';
    $submitText = $isEdit ? 'Modifier la dépense' : 'Enregistrer la dépense';
@endphp

<x-card>
    <x-slot name="header">
        <div class="flex items-center justify-between">
            <h3 class="text-lg font-semibold text-gray-900 dark:text-white">{{ $title }}</h3>
            <x-button href="{{ route('provider.finances.index', ['tab' => 'depenses']) }}" variant="secondary" size="sm">
                <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path>
                </svg>
                Retour
            </x-button>
        </div>
    </x-slot>

    <form action="{{ $action }}" method="POST" class="space-y-6 pb-24" x-data="{
        showNewTypeForm: false,
        showNewSupplierForm: false,
        errorMessage: '',
        showError: false,
        newType: { name: '', description: '', is_active: true },
        newSupplier: { name: '', phone: '', email: '', address: '' },
        async createType() {
            if (!this.newType.name) {
                this.errorMessage = 'Le nom est requis';
                this.showError = true;
                setTimeout(() => { this.showError = false; }, 3000);
                return;
            }
            try {
                const response = await fetch('{{ route("provider.expense-types.store") }}', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': '{{ csrf_token() }}', 'Accept': 'application/json' },
                    body: JSON.stringify(this.newType)
                });
                const data = await response.json();
                if (response.ok && data.success) {
                    const select = document.querySelector('[name=expense_type_id]');
                    const option = new Option(data.expenseType.name, data.expenseType.id, true, true);
                    select.add(option);
                    this.showNewTypeForm = false;
                    this.newType = { name: '', description: '', is_active: true };
                } else {
                    this.errorMessage = data.message || 'Erreur';
                    this.showError = true;
                    setTimeout(() => { this.showError = false; }, 3000);
                }
            } catch (error) {
                this.errorMessage = 'Erreur lors de la création';
                this.showError = true;
                setTimeout(() => { this.showError = false; }, 3000);
            }
        },
        async createSupplier() {
            if (!this.newSupplier.name) {
                this.errorMessage = 'Le nom est requis';
                this.showError = true;
                setTimeout(() => { this.showError = false; }, 3000);
                return;
            }
            try {
                const response = await fetch('{{ route("provider.suppliers.store") }}', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': '{{ csrf_token() }}', 'Accept': 'application/json' },
                    body: JSON.stringify(this.newSupplier)
                });
                const data = await response.json();
                if (response.ok && data.success) {
                    const select = document.querySelector('[name=supplier_id]');
                    const option = new Option(data.supplier.name, data.supplier.id, true, true);
                    select.add(option);
                    this.showNewSupplierForm = false;
                    this.newSupplier = { name: '', phone: '', email: '', address: '' };
                } else {
                    this.errorMessage = data.message || 'Erreur';
                    this.showError = true;
                    setTimeout(() => { this.showError = false; }, 3000);
                }
            } catch (error) {
                this.errorMessage = 'Erreur lors de la création';
                this.showError = true;
                setTimeout(() => { this.showError = false; }, 3000);
            }
        }
    }">
        @csrf
        @if($isEdit)
            @method('PUT')
        @endif
        
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
                <div class="flex items-center justify-between mb-2">
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300">Type de dépense <span class="text-red-500">*</span></label>
                    <button type="button" @click="showNewTypeForm = !showNewTypeForm" class="text-xs text-primary hover:text-primary-dark font-medium">
                        <span x-show="!showNewTypeForm">+ Nouveau type</span>
                        <span x-show="showNewTypeForm" x-cloak>Annuler</span>
                    </button>
                </div>
                <x-select name="expense_type_id" error="{{ $errors->first('expense_type_id') }}" required x-show="!showNewTypeForm">
                    <option value="">Sélectionner un type</option>
                    @foreach($expenseTypes as $type)
                        <option value="{{ $type->id }}" {{ old('expense_type_id', $isEdit ? $expense->expense_type_id : '') == $type->id ? 'selected' : '' }}>
                            {{ $type->name }}
                        </option>
                    @endforeach
                </x-select>
                <div x-show="showNewTypeForm" x-cloak class="border border-gray-300 dark:border-gray-600 rounded-lg p-4 bg-gray-50 dark:bg-gray-700">
                    <div x-show="showError" class="mb-3 bg-red-50 border-l-4 border-red-500 p-3 rounded-r-lg">
                        <div class="flex items-start">
                            <svg class="h-5 w-5 text-red-500 mt-0.5" fill="currentColor" viewBox="0 0 20 20">
                                <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd"/>
                            </svg>
                            <p class="ml-3 text-sm font-medium text-red-800" x-text="errorMessage"></p>
                        </div>
                    </div>
                    <div class="grid grid-cols-2 gap-3">
                        <input type="text" x-model="newType.name" placeholder="Nom *" class="px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 dark:bg-gray-800 dark:text-white rounded-lg">
                        <input type="text" x-model="newType.description" placeholder="Description" class="px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 dark:bg-gray-800 dark:text-white rounded-lg">
                        <div class="col-span-2">
                            <button type="button" @click="createType()" class="w-full bg-primary hover:bg-primary-dark text-white py-2 text-sm rounded-lg transition-colors">Créer le type</button>
                        </div>
                    </div>
                </div>
            </div>

            <div>
                <div class="flex items-center justify-between mb-2">
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300">Fournisseur (optionnel)</label>
                    <button type="button" @click="showNewSupplierForm = !showNewSupplierForm" class="text-xs text-primary hover:text-primary-dark font-medium">
                        <span x-show="!showNewSupplierForm">+ Nouveau fournisseur</span>
                        <span x-show="showNewSupplierForm" x-cloak>Annuler</span>
                    </button>
                </div>
                <x-select name="supplier_id" x-show="!showNewSupplierForm">
                    <option value="">Aucun fournisseur spécifique</option>
                    @foreach($suppliers as $supplier)
                        <option value="{{ $supplier->id }}" {{ old('supplier_id', $isEdit ? $expense->supplier_id : '') == $supplier->id ? 'selected' : '' }}>
                            {{ $supplier->name }}
                        </option>
                    @endforeach
                </x-select>
                <div x-show="showNewSupplierForm" x-cloak class="border border-gray-300 dark:border-gray-600 rounded-lg p-4 bg-gray-50 dark:bg-gray-700">
                    <div x-show="showError" class="mb-3 bg-red-50 border-l-4 border-red-500 p-3 rounded-r-lg">
                        <div class="flex items-start">
                            <svg class="h-5 w-5 text-red-500 mt-0.5" fill="currentColor" viewBox="0 0 20 20">
                                <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd"/>
                            </svg>
                            <p class="ml-3 text-sm font-medium text-red-800" x-text="errorMessage"></p>
                        </div>
                    </div>
                    <div class="grid grid-cols-2 gap-3">
                        <input type="text" x-model="newSupplier.name" placeholder="Nom *" class="px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 dark:bg-gray-800 dark:text-white rounded-lg">
                        <input type="tel" x-model="newSupplier.phone" placeholder="Téléphone" class="px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 dark:bg-gray-800 dark:text-white rounded-lg">
                        <div class="col-span-2">
                            <button type="button" @click="createSupplier()" class="w-full bg-primary hover:bg-primary-dark text-white py-2 text-sm rounded-lg transition-colors">Créer le fournisseur</button>
                        </div>
                    </div>
                </div>
            </div>

            <x-input 
                type="number" 
                name="amount" 
                label="Montant" 
                value="{{ old('amount', $isEdit ? $expense->amount : '') }}"
                step="0.01"
                min="0"
                required
                placeholder="0.00"
                error="{{ $errors->first('amount') }}"
            />

            <x-input 
                type="date" 
                name="expense_date" 
                label="Date de dépense" 
                value="{{ old('expense_date', $isEdit ? $expense->expense_date->format('Y-m-d') : date('Y-m-d')) }}"
                required
                error="{{ $errors->first('expense_date') }}"
            />

            <x-select name="payment_method" label="Mode de paiement" required error="{{ $errors->first('payment_method') }}">
                <option value="cash" {{ old('payment_method', $isEdit ? $expense->payment_method : 'cash') === 'cash' ? 'selected' : '' }}>Espèces</option>
                <option value="card" {{ old('payment_method', $isEdit ? $expense->payment_method : '') === 'card' ? 'selected' : '' }}>Carte</option>
                <option value="bank_transfer" {{ old('payment_method', $isEdit ? $expense->payment_method : '') === 'bank_transfer' ? 'selected' : '' }}>Virement bancaire</option>
                <option value="other" {{ old('payment_method', $isEdit ? $expense->payment_method : '') === 'other' ? 'selected' : '' }}>Autre</option>
            </x-select>

            <x-input 
                type="text" 
                name="reference" 
                label="Référence" 
                value="{{ old('reference', $isEdit ? $expense->reference : '') }}"
                placeholder="Numéro de facture, ticket, etc."
            />

            <div class="md:col-span-2">
                <x-textarea 
                    name="notes" 
                    label="Notes" 
                    rows="3"
                    placeholder="Notes optionnelles sur cette dépense..."
                    value="{{ old('notes', $isEdit ? $expense->notes : '') }}"
                />
            </div>
        </div>

        <!-- Bouton fixe au-dessus de la navigation du bas -->
        <div class="fixed bottom-16 left-0 right-0 p-4 bg-white dark:bg-gray-800 border-t border-gray-200 dark:border-gray-700 shadow-lg z-40">
            <div class="flex gap-3">
                <x-button href="{{ route('provider.finances.index', ['tab' => 'depenses']) }}" variant="secondary" class="flex-1">
                    Annuler
                </x-button>
                <x-button type="submit" class="flex-1">
                    {{ $submitText }}
                </x-button>
            </div>
        </div>
    </form>
</x-card>