@php
    $canManagePatients = app(\App\Services\Care\CarePermissions::class)->can(
        auth()->user() ? app(\App\Services\Care\OrganizationResolver::class)->memberFor(auth()->user(), $organization) : null,
        'patients.manage'
    );
@endphp

<x-app-layout title="Patients">
    <div class="space-y-6">
        <x-care.page-hero
            badge="Records · Search · Registration"
            title="Patients"
            description="Search and manage patient records, demographics, and visit history across your branches."
            :stats="[
                ['value' => number_format($heroStats['total']), 'label' => 'Patients'],
                ['value' => number_format($heroStats['new_this_month']), 'label' => 'New this month'],
                ['value' => number_format($heroStats['with_visits']), 'label' => 'With visits'],
            ]">
            @if ($canManagePatients)
                <x-slot name="actions">
                    <a href="{{ route('care.patients.create') }}" class="btn-primary">Register patient</a>
                </x-slot>
            @endif
        </x-care.page-hero>

        @if (request('focus') === 'assessments')
            <div class="rounded-2xl border border-sky-100 bg-sky-50 px-4 py-3 text-sm text-sky-900">
                <p class="font-medium">Clinical forms</p>
                <p class="mt-1 text-sky-800/90">
                    Open a patient to review history forms and condition-specific scores, or start a visit from
                    <a href="{{ route('care.queue.index') }}" class="font-medium underline">Queue</a>
                    and use the patient history form and condition pathways on the consultation.
                </p>
            </div>
        @endif

        <form method="GET" class="flex flex-wrap gap-3 rounded-2xl border border-slate-200 bg-white p-4">
            <input type="search" name="q" value="{{ request('q') }}" placeholder="Name, phone, patient ID, national ID…"
                   class="min-w-[200px] flex-1 rounded-lg border-slate-300 text-sm">
            <input type="date" name="date_of_birth" value="{{ request('date_of_birth') }}"
                   class="rounded-lg border-slate-300 text-sm" title="Date of birth">
            <button type="submit" class="btn-primary">Search</button>
            @if (request()->hasAny(['q', 'date_of_birth', 'phone', 'national_id', 'patient_number', 'focus']))
                <a href="{{ route('care.patients.index') }}" class="rounded-lg border border-slate-200 px-4 py-2 text-sm text-slate-600">Clear</a>
            @endif
        </form>

        <div class="rounded-2xl border border-slate-200 bg-white p-4"
             x-data="patientScan({ lookupUrl: @js(route('care.patients.scan')) })"
             @keydown.window="onGlobalKeydown($event)">
            <label for="patient-barcode-scan" class="text-sm font-medium text-slate-700">Barcode / QR scan</label>
            <p class="mt-0.5 text-xs text-slate-400">USB scanners work as a keyboard wedge. Scan a patient ID label or type the number and press Enter.</p>
            <div class="mt-2 flex flex-wrap gap-2">
                <input type="text" id="patient-barcode-scan" x-ref="scanInput" x-model="scanCode"
                       @keydown.enter.prevent="submitScan()"
                       placeholder="Scan patient ID…" autocomplete="off"
                       class="min-w-[220px] flex-1 rounded-lg border-slate-300 font-mono text-sm">
                <button type="button" class="btn-primary" @click="submitScan()">Open patient</button>
            </div>
            <p x-show="scanError" x-text="scanError" class="mt-2 text-sm text-rose-600" x-cloak></p>
            <p x-show="scanOk" x-text="scanOk" class="mt-2 text-sm text-emerald-600" x-cloak></p>
        </div>

        <div class="overflow-hidden rounded-2xl border border-slate-200 bg-white">
            <table class="min-w-full text-sm">
                <thead class="bg-slate-50 text-left text-xs uppercase text-slate-500">
                    <tr>
                        <th class="px-4 py-3">Patient</th>
                        <th class="px-4 py-3">Patient ID</th>
                        <th class="px-4 py-3">Phone</th>
                        <th class="px-4 py-3">DOB</th>
                        <th class="px-4 py-3">Branch</th>
                        <th class="px-4 py-3"></th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-slate-50">
                    @forelse ($patients as $patient)
                        <tr>
                            <td class="px-4 py-3">
                                <p class="font-medium text-slate-900">{{ $patient->fullName() }}</p>
                                @if ($patient->national_id)
                                    <p class="text-xs text-slate-500">NID: {{ $patient->national_id }}</p>
                                @endif
                            </td>
                            <td class="px-4 py-3 font-mono text-xs">{{ $patient->patient_number }}</td>
                            <td class="px-4 py-3">{{ $patient->phone ?? '—' }}</td>
                            <td class="px-4 py-3">{{ $patient->date_of_birth?->format('Y-m-d') ?? '—' }}</td>
                            <td class="px-4 py-3">{{ $patient->branch?->name ?? '—' }}</td>
                            <td class="px-4 py-3 text-right">
                                <a href="{{ route('care.patients.show', $patient) }}" class="text-sky-600 hover:text-sky-700">View</a>
                            </td>
                        </tr>
                    @empty
                        <tr>
                            <td colspan="6" class="px-4 py-8 text-center text-slate-500">No patients found.</td>
                        </tr>
                    @endforelse
                </tbody>
            </table>
        </div>

        <div>{{ $patients->links() }}</div>
    </div>
    <script>
        function patientScan(config) {
            return {
                lookupUrl: config.lookupUrl,
                scanCode: '',
                scanError: '',
                scanOk: '',
                scanBuffer: '',
                scanTimer: null,
                submitScan() {
                    const code = (this.scanCode || '').trim();
                    this.scanError = '';
                    this.scanOk = '';
                    if (!code) return;
                    fetch(this.lookupUrl + '?' + new URLSearchParams({ code }), {
                        headers: {
                            Accept: 'application/json',
                            'X-Requested-With': 'XMLHttpRequest',
                        },
                        credentials: 'same-origin',
                    }).then(async (res) => {
                        const data = await res.json().catch(() => ({}));
                        if (!res.ok) {
                            this.scanError = data.message || 'No patient found for that barcode.';
                            return;
                        }
                        this.scanOk = 'Opening ' + (data.patient?.name || 'patient') + '…';
                        window.location.href = data.patient.url;
                    }).catch(() => {
                        this.scanError = 'Lookup failed. Try again.';
                    });
                },
                onGlobalKeydown(e) {
                    if (this.shouldIgnoreScan(e)) return;
                    if (e.key === 'Enter') {
                        const code = (this.scanBuffer || '').trim();
                        this.scanBuffer = '';
                        if (code.length >= 3) {
                            e.preventDefault();
                            this.scanCode = code;
                            this.submitScan();
                        }
                        return;
                    }
                    if (e.key.length === 1 && !e.ctrlKey && !e.metaKey && !e.altKey) {
                        this.scanBuffer += e.key;
                        clearTimeout(this.scanTimer);
                        this.scanTimer = setTimeout(() => { this.scanBuffer = ''; }, 120);
                    }
                },
                shouldIgnoreScan(e) {
                    const tag = (e.target?.tagName || '').toLowerCase();
                    if (tag === 'textarea') return true;
                    if (tag === 'input' && e.target?.id !== 'patient-barcode-scan') return true;
                    if (e.target?.isContentEditable) return true;
                    return false;
                },
            };
        }
    </script>
</x-app-layout>
