<x-app-layout>
    <x-slot name="header">
        <div class="rounded-2xl border border-sky-200/70 bg-gradient-to-r from-sky-50 to-emerald-50 px-5 py-4">
            <h2 class="font-semibold text-xl text-sky-900 leading-tight">
                {{ __('Document Upload & OCR Processing') }}
            </h2>
            <p class="mt-1 text-sm text-sky-700">Upload invoices, BOLs, receipts, or rate confirmations. The system will identify key load details and store a rate snapshot for profit/loss reporting.</p>
        </div>
    </x-slot>

    <div class="py-12">
        <div class="max-w-6xl mx-auto space-y-6 sm:px-6 lg:px-8">
            @if (session('success'))
                <div class="rounded-xl border border-green-200 bg-green-50 p-4 text-green-800 shadow-sm">
                    <p class="font-semibold">{{ session('success') }}</p>
                    @if (session('processedLoad'))
                        <div class="mt-3 grid gap-3 text-sm sm:grid-cols-2 lg:grid-cols-3">
                            <div><span class="font-semibold">Load:</span> {{ session('processedLoad.load_number') }}</div>
                            <div><span class="font-semibold">Company:</span> {{ session('processedLoad.company_name') }}</div>
                            <div><span class="font-semibold">Commodity:</span> {{ session('processedLoad.commodity') }}</div>
                            <div><span class="font-semibold">Miles:</span> {{ session('processedLoad.miles') }}</div>
                            <div><span class="font-semibold">Revenue:</span> ${{ number_format((float) session('processedLoad.revenue'), 2) }}</div>
                            <div><span class="font-semibold">Profit/Loss:</span> ${{ number_format((float) session('processedLoad.profit'), 2) }}</div>
                        </div>
                    @endif
                </div>
            @endif

            @if (session('warning'))
                <div class="rounded-xl border border-amber-200 bg-amber-50 p-4 text-amber-900 shadow-sm">
                    <p class="font-semibold">{{ session('warning') }}</p>
                    <p class="mt-1 text-sm">The file was saved, but extracted values should be reviewed before relying on analytics.</p>
                    @if (session('processedLoad'))
                        <div class="mt-3 grid gap-3 text-sm sm:grid-cols-2 lg:grid-cols-3">
                            <div><span class="font-semibold">Load:</span> {{ session('processedLoad.load_number') }}</div>
                            <div><span class="font-semibold">Company:</span> {{ session('processedLoad.company_name') }}</div>
                            <div><span class="font-semibold">Commodity:</span> {{ session('processedLoad.commodity') }}</div>
                            <div><span class="font-semibold">Miles:</span> {{ session('processedLoad.miles') }}</div>
                            <div><span class="font-semibold">Revenue:</span> ${{ number_format((float) session('processedLoad.revenue'), 2) }}</div>
                            <div><span class="font-semibold">Profit/Loss:</span> ${{ number_format((float) session('processedLoad.profit'), 2) }}</div>
                        </div>
                    @endif
                </div>
            @endif

            @if ($errors->any())
                <div class="rounded-xl border border-rose-200 bg-rose-50 p-4 text-rose-800 shadow-sm">
                    <p class="font-semibold">Upload could not be processed</p>
                    <p class="mt-1 text-sm">Please fix the fields below and select the document file again before submitting.</p>
                    <ul class="mt-2 list-disc space-y-1 pl-5 text-sm">
                        @foreach ($errors->all() as $error)
                            <li>{{ $error }}</li>
                        @endforeach
                    </ul>
                </div>
            @endif

            <div class="grid items-start gap-6 lg:grid-cols-[2fr,1fr]">
                <div class="overflow-hidden rounded-2xl border border-sky-200 bg-gradient-to-br from-white to-sky-50 p-8 shadow-xl">
                    <form method="POST" action="{{ route('documents.store') }}" enctype="multipart/form-data" class="space-y-8">
                        @csrf

                        <div>
                            <h3 class="text-lg font-semibold text-gray-900">1. Upload Document</h3>
                            <p class="mt-1 text-sm text-gray-500">Works with varying PDF/image layouts. If OCR misses a value, use the optional override fields below.</p>
                        </div>

                        <div class="grid gap-6 md:grid-cols-2">
                            <div>
                                <x-input-label for="document_file" :value="__('Document File')" />
                                <input id="document_file" class="mt-1 block w-full rounded-xl border-sky-200 text-sm shadow-sm file:mr-4 file:rounded-full file:border-0 file:bg-cyan-50 file:px-4 file:py-2 file:font-semibold file:text-sky-700 hover:file:bg-cyan-100" type="file" name="document_file" accept=".pdf,.jpg,.jpeg,.png" required />
                                <x-input-error :messages="$errors->get('document_file')" class="mt-2" />
                                <p class="mt-2 text-sm text-gray-500">PDF, JPG, JPEG, or PNG up to 20MB.</p>
                            </div>
<!-- 
                            <div>
                                <x-input-label for="document_type" :value="__('Document Type')" />
                                <select id="document_type" name="document_type" class="mt-1 block w-full rounded-lg border-gray-300 shadow-sm focus:border-emerald-500 focus:ring-emerald-500">
                                    <option value="rate_confirmation" @selected(old('document_type', 'rate_confirmation') === 'rate_confirmation')>Rate Confirmation</option>
                                    <option value="invoice" @selected(old('document_type') === 'invoice')>Invoice</option>
                                    <option value="bol" @selected(old('document_type') === 'bol')>Bill of Lading</option>
                                    <option value="receipt" @selected(old('document_type') === 'receipt')>Receipt</option>
                                    <option value="other" @selected(old('document_type') === 'other')>Other</option>
                                </select>
                                <x-input-error :messages="$errors->get('document_type')" class="mt-2" />
                            </div> -->
<!-- 
                            <div>
                                <x-input-label for="load_number" :value="__('Load / Registration ID (optional)')" />
                                <x-text-input id="load_number" class="block mt-1 w-full" type="text" name="load_number" :value="old('load_number')" />
                                <x-input-error :messages="$errors->get('load_number')" class="mt-2" />
                                <p class="mt-2 text-sm text-gray-500">Leave blank to let OCR identify the registration or load number automatically.</p>
                            </div> -->

                            @if(auth()->user()->role === 'owner')
                                <div>
                                    <x-input-label for="driver_id" :value="__('Assign Driver')" />
                                    <select id="driver_id" name="driver_id" class="mt-1 block w-full rounded-lg border-gray-300 shadow-sm focus:border-emerald-500 focus:ring-emerald-500">
                                        <option value="">Select driver</option>
                                        @foreach($drivers as $driver)
                                            <option value="{{ $driver->id }}" @selected((string) old('driver_id') === (string) $driver->id)>
                                                {{ $driver->name }}{{ $driver->truck?->number ? ' — ' . $driver->truck->number : '' }}
                                            </option>
                                        @endforeach
                                    </select>
                                    <x-input-error :messages="$errors->get('driver_id')" class="mt-2" />
                                </div>
                            @else
                                <div class="rounded-lg border border-blue-200 bg-blue-50 p-4 text-sm text-blue-800">
                                    <p class="font-semibold">Driver upload mode</p>
                                    <p class="mt-1">This upload will be automatically mapped to your logged-in driver profile.</p>
                                </div>
                            @endif
                        </div>

                        <!-- <div class="border-t pt-6">
                            <h3 class="text-lg font-semibold text-gray-900">2. Rate Snapshot</h3>
                            <p class="mt-1 text-sm text-gray-500">These values are saved on the load so later rate changes do not affect existing calculations. If OCR does not detect rate from the document, enter Rate / Mile or Fixed Rate / Load before upload.</p>

                            <div class="mt-4 grid gap-6 md:grid-cols-2 lg:grid-cols-4">
                                <div>
                                    <x-input-label for="rate_type" :value="__('Rate Type')" />
                                    <select id="rate_type" name="rate_type" class="mt-1 block w-full rounded-lg border-gray-300 shadow-sm focus:border-emerald-500 focus:ring-emerald-500">
                                        <option value="per_mile" @selected(old('rate_type', ($company?->default_rate_per_load ? 'per_load' : 'per_mile')) === 'per_mile')>Per Mile</option>
                                        <option value="per_load" @selected(old('rate_type', ($company?->default_rate_per_load ? 'per_load' : 'per_mile')) === 'per_load')>Per Load</option>
                                    </select>
                                </div>

                                <div>
                                    <x-input-label for="rate_per_mile" :value="__('Rate / Mile')" />
                                    <x-text-input id="rate_per_mile" class="block mt-1 w-full" type="number" step="0.01" min="0" name="rate_per_mile" :value="old('rate_per_mile', $company?->default_rate_per_mile)" />
                                    <x-input-error :messages="$errors->get('rate_per_mile')" class="mt-2" />
                                </div>

                                <div>
                                    <x-input-label for="rate_per_load" :value="__('Fixed Rate / Load')" />
                                    <x-text-input id="rate_per_load" class="block mt-1 w-full" type="number" step="0.01" min="0" name="rate_per_load" :value="old('rate_per_load', $company?->default_rate_per_load)" />
                                    <x-input-error :messages="$errors->get('rate_per_load')" class="mt-2" />
                                </div>

                                <div>
                                    <x-input-label for="additional_charge" :value="__('Additional Charges')" />
                                    <x-text-input id="additional_charge" class="block mt-1 w-full" type="number" step="0.01" min="0" name="additional_charge" :value="old('additional_charge', $company?->default_additional_charge ?? 0)" />
                                    <x-input-error :messages="$errors->get('additional_charge')" class="mt-2" />
                                </div>
                            </div>
                        </div> -->

                        <!-- <div class="border-t pt-6">
                            <h3 class="text-lg font-semibold text-gray-900">3. Optional Overrides</h3>
                            <p class="mt-1 text-sm text-gray-500">Useful when document text varies and OCR needs a little help.</p>

                            <div class="mt-4 grid gap-6 md:grid-cols-2 lg:grid-cols-3">
                                <div>
                                    <x-input-label for="miles" :value="__('Distance / Miles (auto-read from document)')" />
                                    <x-text-input id="miles" class="block mt-1 w-full bg-slate-50" type="text" value="Auto-detected from document OCR" readonly />
                                    <p class="mt-2 text-xs text-slate-500">Miles are always extracted from the uploaded document text.</p>
                                </div>
                                <div>
                                    <x-input-label for="weight" :value="__('Weight')" />
                                    <x-text-input id="weight" class="block mt-1 w-full" type="number" step="0.01" min="0" name="weight" :value="old('weight')" />
                                </div>
                                <div>
                                    <x-input-label for="company_name" :value="__('Company Name')" />
                                    <x-text-input id="company_name" class="block mt-1 w-full" type="text" name="company_name" :value="old('company_name')" />
                                </div>
                                <div>
                                    <x-input-label for="commodity" :value="__('Commodity')" />
                                    <x-text-input id="commodity" class="block mt-1 w-full" type="text" name="commodity" :value="old('commodity')" />
                                </div>
                                <div>
                                    <x-input-label for="pickup_location" :value="__('Pickup Location')" />
                                    <x-text-input id="pickup_location" class="block mt-1 w-full" type="text" name="pickup_location" :value="old('pickup_location')" />
                                </div>
                                <div>
                                    <x-input-label for="delivery_location" :value="__('Delivery Location')" />
                                    <x-text-input id="delivery_location" class="block mt-1 w-full" type="text" name="delivery_location" :value="old('delivery_location')" />
                                </div>
                            </div>
                        </div> -->

                        <div class="flex items-center gap-4">
                            <x-primary-button>
                                {{ __('Upload & Process') }}
                            </x-primary-button>
                            <a href="{{ route('dashboard') }}" class="text-gray-600 hover:text-gray-900">Cancel</a>
                        </div>
                    </form>
                </div>

                <div class="space-y-6">
                    <div class="rounded-lg border border-blue-100 bg-blue-50 p-5 shadow-sm">
                        <h3 class="text-sm font-semibold uppercase tracking-wide text-blue-900">Detected Fields</h3>
                        <ul class="mt-3 space-y-2 text-sm text-blue-800">
                            <li>• Pickup & delivery date</li>
                            <li>• Distance / mileage</li>
                            <li>• Weight</li>
                            <li>• Company name</li>
                            <li>• Commodity type</li>
                            <li>• Registration / load ID</li>
                        </ul>
                    </div>

                    <div class="rounded-lg border border-slate-200 bg-white p-5 shadow-sm">
                        <h3 class="text-sm font-semibold uppercase tracking-wide text-slate-900">Recent Processed Loads</h3>
                        <div class="mt-3 space-y-3 text-sm text-slate-600">
                            @forelse($recentLoads as $load)
                                <div class="rounded-lg border border-slate-100 p-3">
                                    <p class="font-semibold text-slate-900">{{ $load->load_number }}</p>
                                    <p>{{ $load->driver?->name ?? 'Unassigned driver' }} • {{ $load->broker_company }}</p>
                                    <p>${{ number_format((float) $load->gross_rate, 2) }} revenue • ${{ number_format((float) $load->net_profit, 2) }} profit</p>
                                </div>
                            @empty
                                <p>No documents processed yet.</p>
                            @endforelse
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</x-app-layout>

