@assets
    {{ module_vite('build-tailwind_theme', 'resources/views/themes/tailwind_theme/assets/components/contact-form.css', storage_path('vite-tailwind_theme.hot')) }}
@endassets

<?php

use Livewire\Component;
use Livewire\Attributes\Validate;
use Modules\Laundry\Models\Service;
use Modules\Laundry\Models\Garment;
use Modules\Laundry\Models\ServicePrice;
use Vinkla\Hashids\Facades\Hashids;

new class extends Component {
    public string $formTitle = 'Schedule a Pickup';
    public array $formLabels = [];

    /** Dropdown data */
    public array $services = [];
    public array $garments = [];

    /** Items (repeatable service/garment/quantity) */
    public array $items = [['service' => '', 'garment' => '', 'quantity' => 1, 'price' => null, 'expressPrice' => null]];

    /** Express Delivery Option */
    public bool $isExpress = false;

    /** Form fields */
    #[Validate('required|string|max:255')]
    public string $name = '';

    #[Validate('required|string|max:20')]
    public string $phone = '';

    #[Validate('required|email|max:255')]
    public string $email = '';

    #[Validate('required|date')]
    public string $date = '';

    #[Validate('nullable|string|max:1000')]
    public string $message = '';

    /** UI State */
    public bool $submitted = false;
    public string $submitStatus = '';
    public string $submitMessage = '';

    public function mount(string $formTitle = 'Schedule a Pickup', array $formLabels = [])
    {
        $this->formTitle = $formTitle;

        $this->formLabels = array_merge(
            [
                'name' => 'Full Name',
                'phone' => 'Phone Number',
                'email' => 'Email Address',
                'service' => 'Service Type',
                'service_placeholder' => 'Select a service',
                'garment' => 'Garment Type',
                'garment_placeholder' => 'Select a garment',
                'date' => 'Preferred Pickup Date',
                'notes' => 'Additional Notes',
                'notes_placeholder' => 'Any special instructions...',
                'submit' => 'Schedule Pickup',
                'price' => 'Price',
                'express_price' => 'Express Price',
                'express_delivery' => 'Express Delivery',
                'express_delivery_note' => 'Get your items delivered faster',
            ],
            $formLabels,
        );

        /** Load dropdown data ONCE */
        $this->services = Service::orderBy('name')->get()->map(fn($s) => ['xid' => $s->xid, 'name' => $s->name])->toArray();

        $this->garments = Garment::orderBy('name')->get()->map(fn($g) => ['xid' => $g->xid, 'name' => $g->name])->toArray();
    }

    public function addItem(): void
    {
        $this->items[] = ['service' => '', 'garment' => '', 'quantity' => 1, 'price' => null, 'expressPrice' => null];
    }

    public function removeItem(int $index): void
    {
        if (count($this->items) > 1) {
            unset($this->items[$index]);
            $this->items = array_values($this->items);
        }
    }

    public function updatedItems($value, $key): void
    {
        // Extract index and field from the key (e.g., "0.service" -> index=0, field=service)
        $parts = explode('.', $key);
        if (count($parts) !== 2) {
            return;
        }

        $index = (int) $parts[0];
        $field = $parts[1];

        // Auto-calculate price when service or garment changes
        if (in_array($field, ['service', 'garment'])) {
            $this->calculatePrice($index);
        }
    }

    public function calculatePrice(int $index): void
    {
        $item = $this->items[$index] ?? null;

        if (!$item || !$item['service'] || !$item['garment']) {
            // Reset prices if service or garment is empty
            if (isset($this->items[$index])) {
                $this->items[$index]['price'] = null;
                $this->items[$index]['expressPrice'] = null;
            }
            return;
        }

        try {
            $serviceId = Hashids::decode($item['service'])[0] ?? null;
            $garmentId = Hashids::decode($item['garment'])[0] ?? null;

            if (!$serviceId || !$garmentId) {
                return;
            }

            $servicePrice = ServicePrice::withoutGlobalScopes()->where('service_id', $serviceId)->where('garment_id', $garmentId)->first();

            if ($servicePrice) {
                $this->items[$index]['price'] = $servicePrice->price;
                $this->items[$index]['expressPrice'] = $servicePrice->express_price;
            } else {
                $this->items[$index]['price'] = null;
                $this->items[$index]['expressPrice'] = null;
            }
        } catch (\Throwable $e) {
            logger()->error('Price calculation failed', [
                'index' => $index,
                'service' => $item['service'],
                'garment' => $item['garment'],
                'error' => $e->getMessage(),
            ]);
        }
    }

    public function submit(): void
    {
        $this->validate();

        $this->submitted = true;
        $this->submitStatus = 'success';
        $this->submitMessage = 'Thank you! Your pickup request has been submitted successfully.';

        $this->reset(['name', 'phone', 'email', 'date', 'message']);
        $this->items = [['service' => '', 'garment' => '', 'quantity' => 1, 'price' => null, 'expressPrice' => null]];
    }

    public function resetForm(): void
    {
        $this->reset();
    }
};
?>

<div>
    <div class="bg-white dark:bg-gray-800 rounded-2xl shadow-xl p-8">

        <h3 class="text-2xl font-bold text-gray-900 dark:text-white mb-6">{{ $formTitle }}</h3>

        @if ($submitted)
            <div
                class="mb-6 p-4 rounded bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-700 text-green-800 dark:text-green-300">
                {{ $submitMessage }}
                <button wire:click="resetForm"
                    class="float-right text-green-600 dark:text-green-400 hover:text-green-800 dark:hover:text-green-200">✕</button>
            </div>
        @endif

        <form wire:submit.prevent="submit" class="space-y-6">

            <div class="grid md:grid-cols-2 gap-6">
                <div>
                    <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">{{ $formLabels['name'] }}</label>
                    <input type="text" wire:model.defer="name" class="input" placeholder="John Doe">
                    @error('name')
                        <span class="text-red-500 text-sm">{{ $message }}</span>
                    @enderror
                </div>
                <div>
                    <label
                        class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">{{ $formLabels['phone'] }}</label>
                    <input type="tel" wire:model.defer="phone" class="input" placeholder="+1 (555) 123-4567">
                    @error('phone')
                        <span class="text-red-500 text-sm">{{ $message }}</span>
                    @enderror
                </div>
            </div>

            <div>
                <label
                    class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">{{ $formLabels['email'] }}</label>
                <input type="email" wire:model.defer="email" class="input" placeholder="john@example.com">
                @error('email')
                    <span class="text-red-500 text-sm">{{ $message }}</span>
                @enderror
            </div>

            {{-- Items Section --}}
            <div class="space-y-3">
                <div class="flex justify-between items-center mb-2">
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300">Items</label>
                    <button type="button" wire:click="addItem"
                        class="text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 text-sm font-medium">
                        + Add Item
                    </button>
                </div>

                @foreach ($items as $index => $item)
                    <div class="flex gap-3 items-end">
                        <div class="flex-1">
                            @if ($index === 0)
                                <label
                                    class="block text-xs text-gray-600 dark:text-gray-400 mb-1">{{ $formLabels['service'] }}</label>
                            @endif
                            <select wire:model.live="items.{{ $index }}.service" class="input">
                                <option value="">{{ $formLabels['service_placeholder'] }}</option>
                                @foreach ($services as $service)
                                    <option value="{{ $service['xid'] }}">{{ $service['name'] }}</option>
                                @endforeach
                            </select>
                        </div>

                        <div class="flex-1">
                            @if ($index === 0)
                                <label
                                    class="block text-xs text-gray-600 dark:text-gray-400 mb-1">{{ $formLabels['garment'] }}</label>
                            @endif
                            <select wire:model.live="items.{{ $index }}.garment" class="input">
                                <option value="">{{ $formLabels['garment_placeholder'] }}</option>
                                @foreach ($garments as $garment)
                                    <option value="{{ $garment['xid'] }}">{{ $garment['name'] }}</option>
                                @endforeach
                            </select>
                        </div>

                        <div class="w-36">
                            @if ($index === 0)
                                <label class="block text-xs text-gray-600 dark:text-gray-400 mb-1">Quantity</label>
                            @endif
                            <input type="number" wire:model.live="items.{{ $index }}.quantity"
                                class="input h-[51px]" min="1" value="1">
                        </div>

                        <div class="flex items-center justify-center pb-1">
                            <button type="button" wire:click="removeItem({{ $index }})"
                                class="inline-flex items-center justify-center w-10 h-10 rounded-lg transition-colors duration-150 {{ $index === 0 ? 'bg-gray-100 dark:bg-gray-800 text-gray-400 dark:text-gray-600 cursor-not-allowed' : 'bg-red-50 dark:bg-red-900/20 text-red-600 dark:text-red-400 hover:bg-red-100 dark:hover:bg-red-900/30 hover:text-red-700 dark:hover:text-red-300' }}"
                                title="{{ $index === 0 ? 'Cannot remove first item' : 'Remove item' }}"
                                @if ($index === 0) disabled @endif>
                                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                        d="M6 18L18 6M6 6l12 12" />
                                </svg>
                            </button>
                        </div>
                    </div>
                @endforeach
            </div>

            {{-- Express Delivery Toggle --}}
            <div class="express-delivery-box flex items-center space-x-3 p-4 rounded-lg transition-colors">
                <input type="checkbox" wire:model.live="isExpress" id="express-delivery"
                    class="w-5 h-5 text-purple-600 rounded focus:ring-purple-500 cursor-pointer">
                <label for="express-delivery" class="flex-1 cursor-pointer">
                    <span class="express-delivery-title font-medium">{{ $formLabels['express_delivery'] }}</span>
                    <span class="express-delivery-subtitle block text-sm">{{ $formLabels['express_delivery_note'] }}</span>
                </label>
            </div>

            @php
                $totalPrice = 0;
                $hasAnyPrice = false;

                foreach ($items as $item) {
                    $priceToUse = $isExpress ? $item['expressPrice'] ?? $item['price'] : $item['price'];

                    if ($priceToUse !== null) {
                        $totalPrice += $priceToUse * $item['quantity'];
                        $hasAnyPrice = true;
                    }
                }
            @endphp

            @if ($hasAnyPrice)
                <div
                    class="{{ $isExpress ? 'bg-purple-50 dark:bg-purple-900/20 border-purple-200 dark:border-purple-800' : 'bg-blue-50 dark:bg-blue-900/20 border-blue-200 dark:border-blue-800' }} border rounded-lg p-4 transition-colors duration-300">
                    <div class="flex justify-between items-center">
                        <div>
                            <p class="text-sm text-gray-600 dark:text-gray-400">
                                Total {{ $isExpress ? $formLabels['express_price'] : $formLabels['price'] }}
                            </p>
                            <p
                                class="text-3xl font-bold {{ $isExpress ? 'text-purple-600 dark:text-purple-400' : 'text-blue-600 dark:text-blue-400' }}">
                                ${{ number_format($totalPrice, 2) }}
                            </p>
                        </div>
                        @if ($isExpress)
                            <div
                                class="px-3 py-1 bg-purple-100 dark:bg-purple-900/50 text-purple-700 dark:text-purple-300 rounded-full text-sm font-medium">
                                Express
                            </div>
                        @endif
                    </div>
                </div>
            @endif

            <div>
                <label
                    class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">{{ $formLabels['date'] }}</label>
                <input type="date" wire:model.defer="date" class="input" min="{{ date('Y-m-d') }}">
                @error('date')
                    <span class="text-red-500 text-sm">{{ $message }}</span>
                @enderror
            </div>

            <div>
                <label
                    class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">{{ $formLabels['notes'] }}</label>
                <textarea wire:model.defer="message" class="input textarea" placeholder="{{ $formLabels['notes_placeholder'] }}"
                    rows="4"></textarea>
                @error('message')
                    <span class="text-red-500 text-sm">{{ $message }}</span>
                @enderror
            </div>

            <button type="submit" class="btn btn-primary w-full">
                {{ $formLabels['submit'] }}
            </button>

        </form>
    </div>
</div>
