@php
    $plan = $dentalPlan;
    $history = ($dentalPlanHistory ?? collect())->filter(fn ($p) => ! $plan || $p->id !== $plan->id);
    $canManage = $canConsult ?? false;
@endphp

<section class="rounded-2xl border border-slate-200 bg-white p-5">
    <div class="flex flex-wrap items-start justify-between gap-3">
        <div>
            <h3 class="text-sm font-semibold text-slate-900">Treatment plan</h3>
            <p class="mt-0.5 text-xs text-slate-500">
                @if ($plan)
                    Status: <span class="font-medium">{{ ucfirst(str_replace('_', ' ', $plan->status)) }}</span>
                    · Estimate {{ $currency ?? 'GHS' }} {{ number_format($plan->estimate_minor / 100, 2) }}
                @else
                    Create a plan by adding the first item.
                @endif
            </p>
        </div>
        @if ($canManage && $plan)
            <div class="flex flex-wrap gap-2">
                @if ($plan->status === 'draft')
                    <form method="POST" action="{{ route('care.specialty.dentistry.plan.accept', $workspaceVisit) }}">
                        @csrf
                        <button type="submit" class="rounded-lg border border-emerald-200 bg-emerald-50 px-3 py-1.5 text-sm font-medium text-emerald-800 hover:bg-emerald-100">Accept</button>
                    </form>
                @endif
                @if (in_array($plan->status, ['draft', 'accepted'], true))
                    <form method="POST" action="{{ route('care.specialty.dentistry.plan.reject', $workspaceVisit) }}" class="flex gap-1">
                        @csrf
                        <input type="text" name="rejection_reason" placeholder="Reject reason" class="rounded-lg border border-slate-200 px-2 py-1 text-sm">
                        <button type="submit" class="rounded-lg border border-amber-200 bg-amber-50 px-3 py-1.5 text-sm font-medium text-amber-900">Reject</button>
                    </form>
                @endif
                @if ($plan->status !== 'completed')
                    <form method="POST" action="{{ route('care.specialty.dentistry.plan.cancel', $workspaceVisit) }}" onsubmit="return confirm('Cancel this plan?')">
                        @csrf
                        <button type="submit" class="rounded-lg border border-slate-200 px-3 py-1.5 text-sm font-medium text-slate-700">Cancel plan</button>
                    </form>
                @endif
            </div>
        @endif
    </div>

    <ul class="mt-4 space-y-3 text-sm">
        @forelse ($plan?->items ?? [] as $item)
            <li class="rounded-xl border border-slate-100 bg-slate-50 px-3 py-3">
                <div class="flex flex-wrap items-start justify-between gap-2">
                    <div>
                        <p class="font-medium text-slate-800">
                            {{ $item->label }}
                            @if ($item->tooth_code)<span class="text-slate-500">· {{ $item->tooth_code }}</span>@endif
                            @if (! empty($item->surfaces))<span class="text-slate-400">({{ implode('', $item->surfaces) }})</span>@endif
                        </p>
                        <p class="text-xs text-slate-500">Priority {{ $item->priority }} · {{ ucfirst($item->status) }} · {{ number_format($item->estimate_minor / 100, 2) }}</p>
                    </div>
                    @if ($canManage && ! in_array($item->status, ['done', 'cancelled'], true))
                        <form method="POST" action="{{ route('care.specialty.dentistry.plan-items.cancel', [$workspaceVisit, $item]) }}" onsubmit="return confirm('Cancel this item?')">
                            @csrf
                            <button type="submit" class="text-xs font-medium text-rose-600">Cancel item</button>
                        </form>
                    @endif
                </div>
                @if ($canManage && ! in_array($item->status, ['done', 'cancelled'], true))
                    <form method="POST" action="{{ route('care.specialty.dentistry.plan-items.update', [$workspaceVisit, $item]) }}" class="mt-3 grid gap-2 border-t border-slate-200/70 pt-3 sm:grid-cols-4">
                        @csrf
                        <select name="procedure_code" class="rounded-lg border border-slate-200 px-2 py-1.5 text-xs">
                            @foreach ($dentalCatalog as $service)
                                <option value="{{ $service['code'] }}" @selected($item->procedure_code === $service['code'])>{{ $service['label'] }}</option>
                            @endforeach
                        </select>
                        <select name="tooth_code" class="rounded-lg border border-slate-200 px-2 py-1.5 text-xs">
                            <option value="">Tooth</option>
                            @foreach (array_merge($dentalRows['upper'] ?? [], $dentalRows['lower'] ?? []) as $code)
                                <option value="{{ $code }}" @selected($item->tooth_code === $code)>{{ $code }}</option>
                            @endforeach
                        </select>
                        <input type="number" name="priority" value="{{ $item->priority }}" min="1" max="100" class="rounded-lg border border-slate-200 px-2 py-1.5 text-xs">
                        <button type="submit" class="rounded-lg bg-white px-2 py-1.5 text-xs font-semibold text-indigo-700 ring-1 ring-indigo-200">Save</button>
                    </form>
                @endif
            </li>
        @empty
            <li class="text-slate-500">No plan items yet.</li>
        @endforelse
    </ul>

    @if ($canManage && (! $plan || ! in_array($plan->status, ['completed', 'rejected', 'cancelled'], true)))
        <form method="POST" action="{{ route('care.specialty.dentistry.plan-items', $workspaceVisit) }}" class="mt-6 space-y-3 border-t border-slate-100 pt-4">
            @csrf
            <h4 class="text-sm font-semibold text-slate-900">Add item</h4>
            <div class="grid gap-3 sm:grid-cols-2">
                <div>
                    <label class="block text-xs font-medium text-slate-600">Procedure</label>
                    <select name="procedure_code" required class="mt-1 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm">
                        <option value="">Select…</option>
                        @foreach ($dentalCatalog as $service)
                            <option value="{{ $service['code'] }}">{{ $service['label'] }} — {{ number_format(((int) $service['amount_minor']) / 100, 2) }}</option>
                        @endforeach
                    </select>
                </div>
                <div>
                    <label class="block text-xs font-medium text-slate-600">Tooth (FDI)</label>
                    <select name="tooth_code" class="mt-1 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm">
                        <option value="">—</option>
                        @foreach (array_merge($dentalRows['upper'] ?? [], $dentalRows['lower'] ?? []) as $code)
                            <option value="{{ $code }}">{{ $code }}</option>
                        @endforeach
                    </select>
                </div>
                <div>
                    <label class="block text-xs font-medium text-slate-600">Priority (1 = highest)</label>
                    <input type="number" name="priority" value="50" min="1" max="100" class="mt-1 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm">
                </div>
                <div class="sm:col-span-2">
                    <p class="text-xs font-medium text-slate-600">Surfaces</p>
                    <div class="mt-2 flex flex-wrap gap-3">
                        @foreach ($dentalSurfaces as $surface)
                            <label class="inline-flex items-center gap-1.5 text-sm">
                                <input type="checkbox" name="surfaces[]" value="{{ $surface }}" class="rounded border-slate-300 text-indigo-600">
                                {{ $surface }}
                            </label>
                        @endforeach
                    </div>
                </div>
                <div class="sm:col-span-2">
                    <label class="block text-xs font-medium text-slate-600">Notes</label>
                    <input type="text" name="notes" class="mt-1 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm">
                </div>
            </div>
            <button type="submit" class="btn-primary">Add to plan</button>
        </form>
    @endif
</section>

@if ($history->isNotEmpty())
    <section class="mt-4 rounded-2xl border border-slate-200 bg-white p-5">
        <h3 class="text-sm font-semibold text-slate-900">Plan history</h3>
        <ul class="mt-3 space-y-2 text-sm">
            @foreach ($history as $past)
                <li class="flex flex-wrap items-center justify-between gap-2 rounded-xl border border-slate-100 px-3 py-2">
                    <span>{{ $past->title ?: 'Treatment plan' }} · {{ ucfirst(str_replace('_', ' ', $past->status)) }} · {{ $past->items->count() }} items</span>
                    <span class="text-xs text-slate-500">{{ $past->created_at?->format('d M Y') }}</span>
                </li>
            @endforeach
        </ul>
    </section>
@endif
