@extends('layouts.admin')

@section('title', 'Application '.$application->application_number)
@section('heading', 'Application '.$application->application_number)

@section('content')

    @php $applicant = $application->applicant; @endphp

    <div class="mb-6">
        <a href="{{ route('admin.applications.index') }}"
           class="inline-flex items-center gap-1.5 text-sm text-slate-500 transition hover:text-slate-900">
            <svg class="h-4 w-4" fill="currentColor" viewBox="0 0 20 20" aria-hidden="true">
                <path fill-rule="evenodd" d="M17 10a1 1 0 0 1-1 1H6.4l3.3 3.3a1 1 0 1 1-1.4 1.4l-5-5a1 1 0 0 1 0-1.4l5-5a1 1 0 0 1 1.4 1.4L6.4 9H16a1 1 0 0 1 1 1Z" clip-rule="evenodd"/>
            </svg>
            All applications
        </a>
    </div>

    <div class="grid gap-6 xl:grid-cols-3">

        {{-- Applicant record --}}
        <div class="space-y-6 xl:col-span-2" x-data="{ tab: 'personal' }">

            <x-card>
                <div class="flex flex-wrap items-start justify-between gap-4">
                    <div>
                        <h2 class="text-xl font-semibold text-slate-900">{{ $applicant->fullName() }}</h2>
                        <p class="mt-1 text-sm text-slate-600">{{ $applicant->user->email }} &middot; {{ $applicant->phone }}</p>
                        <p class="mt-2 font-mono text-xs text-slate-500">{{ $application->application_number }}</p>
                    </div>

                    <div class="text-right">
                        <x-status-badge :status="$application->status" />
                        <p class="mt-2 text-xs text-slate-500">
                            {{ $application->submitted_at ? 'Submitted '.$application->submitted_at->format('j M Y') : 'Not submitted' }}
                        </p>
                    </div>
                </div>

                {{-- Tabs --}}
                <div class="mt-6 flex flex-wrap gap-1 border-b border-slate-200">
                    @foreach ([
                        'personal' => 'Personal',
                        'academic' => 'Academic',
                        'programme' => 'Programme',
                        'documents' => 'Documents',
                        'payment' => 'Payment',
                        'history' => 'History',
                    ] as $key => $label)
                        <button type="button" @click="tab = '{{ $key }}'"
                                :class="tab === '{{ $key }}'
                                    ? 'border-brand-700 text-brand-800'
                                    : 'border-transparent text-slate-500 hover:text-slate-800'"
                                class="-mb-px border-b-2 px-3 py-2 text-sm font-medium transition">
                            {{ $label }}
                        </button>
                    @endforeach
                </div>

                {{-- Personal --}}
                <div x-show="tab === 'personal'" class="mt-5">
                    <dl class="grid gap-4 text-sm sm:grid-cols-2">
                        @foreach ([
                            'Full name' => $applicant->fullName(),
                            'Date of birth' => $applicant->date_of_birth?->format('j F Y').($applicant->age() ? ' (age '.$applicant->age().')' : ''),
                            'Gender' => $applicant->gender?->label(),
                            'Nationality' => $applicant->nationality,
                            'Identity number' => $applicant->identityNumber(),
                            'Marital status' => $applicant->marital_status ? ucfirst($applicant->marital_status) : null,
                            'Address' => $applicant->address,
                            'District' => $applicant->district,
                            'Country' => $applicant->country,
                            'Next of kin' => $applicant->guardian_name
                                ? $applicant->guardian_name.' ('.$applicant->guardian_relationship.') — '.$applicant->guardian_phone
                                : null,
                        ] as $label => $value)
                            <div>
                                <dt class="text-xs uppercase tracking-wider text-slate-400">{{ $label }}</dt>
                                <dd class="mt-0.5 break-words text-slate-800">{{ $value ?: '—' }}</dd>
                            </div>
                        @endforeach
                    </dl>
                </div>

                {{-- Academic --}}
                <div x-show="tab === 'academic'" x-cloak class="mt-5">
                    @forelse ($applicant->qualifications as $qualification)
                        <div class="mb-4 rounded-lg border border-slate-200 p-4">
                            <div class="flex flex-wrap items-center justify-between gap-2">
                                <x-badge color="brand" size="sm">{{ $qualification->typeLabel() }}</x-badge>
                                <span class="text-xs text-slate-500">
                                    {{ $qualification->year }}
                                    @if ($qualification->index_number)
                                        &middot; {{ $qualification->index_number }}
                                    @endif
                                </span>
                            </div>

                            <p class="mt-2 text-sm font-medium text-slate-900">{{ $qualification->institution }}</p>
                            @if ($qualification->award)
                                <p class="text-sm text-slate-600">{{ $qualification->award }}</p>
                            @endif
                            @if ($qualification->gpa)
                                <p class="text-sm text-slate-600">GPA {{ $qualification->gpa }}</p>
                            @endif

                            @if ($qualification->subjects->isNotEmpty())
                                <table class="mt-3 w-full text-xs">
                                    <thead class="text-left text-slate-400">
                                        <tr>
                                            <th scope="col" class="pb-1 font-medium">Subject</th>
                                            <th scope="col" class="pb-1 font-medium">Grade</th>
                                            <th scope="col" class="pb-1 text-right font-medium">Points</th>
                                        </tr>
                                    </thead>
                                    <tbody class="divide-y divide-slate-100">
                                        @foreach ($qualification->subjects as $subject)
                                            <tr>
                                                <td class="py-1.5 text-slate-700">{{ $subject->subject }}</td>
                                                <td class="py-1.5 font-medium text-slate-900">{{ $subject->grade }}</td>
                                                <td class="py-1.5 text-right text-slate-500">{{ $subject->points ?? '—' }}</td>
                                            </tr>
                                        @endforeach
                                    </tbody>
                                    @if ($qualification->total_points)
                                        <tfoot>
                                            <tr class="border-t border-slate-200">
                                                <td colspan="2" class="pt-1.5 font-medium text-slate-700">Total points</td>
                                                <td class="pt-1.5 text-right font-semibold text-slate-900">{{ $qualification->total_points }}</td>
                                            </tr>
                                        </tfoot>
                                    @endif
                                </table>
                            @endif
                        </div>
                    @empty
                        <p class="text-sm text-slate-500">No qualifications recorded.</p>
                    @endforelse
                </div>

                {{-- Programme + eligibility --}}
                <div x-show="tab === 'programme'" x-cloak class="mt-5">
                    @forelse ($application->choices as $choice)
                        @php $result = $eligibility[$choice->id] ?? null; @endphp

                        <div class="mb-4 rounded-lg border border-slate-200 p-4">
                            <div class="flex items-start justify-between gap-3">
                                <div class="min-w-0">
                                    <p class="text-xs uppercase tracking-wider text-slate-400">Choice {{ $choice->choice_number }}</p>
                                    <p class="mt-1 text-sm font-medium text-slate-900">{{ $choice->programme->name }}</p>
                                    <p class="text-xs text-slate-500">{{ $choice->programme->school->name }}</p>
                                </div>

                                @if ($result)
                                    <x-badge :color="$result->isEligible() ? 'emerald' : 'amber'">
                                        {{ $result->isEligible() ? 'Eligible' : 'Check requirements' }}
                                    </x-badge>
                                @endif
                            </div>

                            @if ($result && $result->checks->isNotEmpty())
                                <ul class="mt-4 space-y-1.5 text-xs">
                                    @foreach ($result->checks as $check)
                                        <li class="flex items-start gap-2">
                                            <span @class([
                                                'mt-1 h-1.5 w-1.5 shrink-0 rounded-full',
                                                'bg-emerald-500' => $check['met'] === true,
                                                'bg-red-500' => $check['met'] === false,
                                                'bg-slate-300' => $check['met'] === null,
                                            ])></span>
                                            <span class="text-slate-600">
                                                {{ $check['description'] }}
                                                @if ($check['met'] === null)
                                                    <span class="text-slate-400">(not assessable)</span>
                                                @endif
                                            </span>
                                        </li>
                                    @endforeach
                                </ul>
                            @endif
                        </div>
                    @empty
                        <p class="text-sm text-slate-500">No programme choices recorded.</p>
                    @endforelse
                </div>

                {{-- Documents --}}
                <div x-show="tab === 'documents'" x-cloak class="mt-5">
                    @forelse ($application->documents as $document)
                        <div class="mb-3 flex flex-wrap items-center justify-between gap-3 rounded-lg border border-slate-200 p-4">
                            <div class="min-w-0 flex-1">
                                <p class="text-sm font-medium text-slate-900">
                                    {{ ucwords(str_replace('-', ' ', $document->document_type)) }}
                                </p>
                                <p class="mt-0.5 truncate text-xs text-slate-500">
                                    {{ $document->original_filename }} &middot; {{ $document->humanSize() }}
                                </p>
                                @if ($document->isRejected() && $document->rejection_reason)
                                    <p class="mt-1 text-xs text-red-600">{{ $document->rejection_reason }}</p>
                                @endif
                            </div>

                            <div class="flex shrink-0 items-center gap-2">
                                <x-status-badge :status="$document->verification_status" />

                                @permission('documents.view')
                                    <a href="{{ route('applicant.documents.preview', $document) }}"
                                       target="_blank" rel="noopener"
                                       class="rounded-lg border border-slate-300 px-2.5 py-1 text-xs font-medium text-slate-700 transition hover:bg-slate-50">
                                        View
                                    </a>
                                @endpermission

                                @permission('documents.verify')
                                    @unless ($document->isVerified())
                                        <form method="POST" action="{{ route('admin.documents.verify', $document) }}">
                                            @csrf
                                            <button type="submit"
                                                    class="rounded-lg bg-emerald-600 px-2.5 py-1 text-xs font-medium text-white transition hover:bg-emerald-700">
                                                Verify
                                            </button>
                                        </form>
                                    @endunless

                                    @unless ($document->isRejected())
                                        <form method="POST" action="{{ route('admin.documents.reject', $document) }}"
                                              x-data
                                              @submit="if (! $refs.reason{{ $document->id }}.value) { $event.preventDefault(); alert('Please give a reason.'); }">
                                            @csrf
                                            <input type="hidden" name="reason" x-ref="reason{{ $document->id }}">
                                            <button type="button"
                                                    @click="$refs.reason{{ $document->id }}.value = prompt('Why is this document being rejected?') || ''; if ($refs.reason{{ $document->id }}.value) $el.closest('form').submit();"
                                                    class="rounded-lg border border-red-300 px-2.5 py-1 text-xs font-medium text-red-700 transition hover:bg-red-50">
                                                Reject
                                            </button>
                                        </form>
                                    @endunless
                                @endpermission
                            </div>
                        </div>
                    @empty
                        <p class="text-sm text-slate-500">No documents uploaded.</p>
                    @endforelse
                </div>

                {{-- Payment --}}
                <div x-show="tab === 'payment'" x-cloak class="mt-5">
                    @forelse ($application->payments as $payment)
                        <div class="mb-3 rounded-lg border border-slate-200 p-4">
                            <div class="flex flex-wrap items-center justify-between gap-3">
                                <div>
                                    <p class="font-mono text-sm text-slate-900">{{ $payment->reference }}</p>
                                    <p class="mt-0.5 text-xs text-slate-500">
                                        {{ ucwords(str_replace('_', ' ', $payment->provider)) }}
                                        @if ($payment->paid_at)
                                            &middot; paid {{ $payment->paid_at->format('j M Y') }}
                                        @endif
                                    </p>
                                </div>

                                <div class="flex items-center gap-3">
                                    <span class="font-semibold text-slate-900">{{ $payment->formattedAmount() }}</span>
                                    <x-status-badge :status="$payment->status" />
                                </div>
                            </div>
                        </div>
                    @empty
                        <p class="text-sm text-slate-500">No payment recorded.</p>
                    @endforelse
                </div>

                {{-- History --}}
                <div x-show="tab === 'history'" x-cloak class="mt-5">
                    <ul class="space-y-3">
                        @foreach ($application->statusHistory as $entry)
                            <li class="flex gap-3 rounded-lg border border-slate-200 p-3 text-sm">
                                <span class="mt-1 h-2 w-2 shrink-0 rounded-full bg-brand-700"></span>
                                <div class="min-w-0">
                                    <p class="text-slate-800">
                                        {{ $entry->from_status?->label() ?? 'Created' }}
                                        <span class="text-slate-400">&rarr;</span>
                                        <strong>{{ $entry->to_status->label() }}</strong>
                                    </p>
                                    @if ($entry->reason)
                                        <p class="mt-0.5 text-xs text-slate-600">{{ $entry->reason }}</p>
                                    @endif
                                    <p class="mt-1 text-xs text-slate-400">
                                        {{ $entry->changedBy?->name ?? 'System' }}
                                        &middot; {{ $entry->created_at?->format('j M Y, g:i A') }}
                                        @if ($entry->ip_address)
                                            &middot; {{ $entry->ip_address }}
                                        @endif
                                    </p>
                                </div>
                            </li>
                        @endforeach
                    </ul>
                </div>
            </x-card>
        </div>

        {{-- Review panel --}}
        <aside class="space-y-6">

            @permission('applications.review')
                <x-card>
                    <h2 class="text-sm font-semibold uppercase tracking-wider text-slate-900">Decision</h2>

                    @if ($transitions === [])
                        <p class="mt-4 text-sm text-slate-500">
                            No further transitions are available to you from this status.
                        </p>
                    @else
                        <form method="POST" action="{{ route('admin.applications.status', $application) }}" class="mt-4 space-y-4">
                            @csrf

                            <x-select name="status" label="Move to" required placeholder="Select a status"
                                      :options="collect($transitions)->mapWithKeys(fn ($s) => [$s->value => $s->label()])->all()" />

                            <x-textarea name="reason" label="Reason / comments" rows="3"
                                        hint="Recorded in the application history."></x-textarea>

                            <x-button type="submit" class="w-full">Update status</x-button>
                        </form>
                    @endif
                </x-card>

                @permission('applications.approve')
                    @if (! $application->admissionRecord && $application->status->canTransitionTo(\App\Enums\ApplicationStatus::Admitted))
                        <x-card class="border-emerald-200 bg-emerald-50">
                            <h2 class="text-sm font-semibold uppercase tracking-wider text-slate-900">Admit applicant</h2>
                            <p class="mt-2 text-xs text-slate-600">
                                This issues an admission number and generates the admission letter.
                            </p>

                            <form method="POST" action="{{ route('admin.admissions.admit', $application) }}" class="mt-4 space-y-4">
                                @csrf

                                <x-select name="programme_id" label="Admit to programme"
                                          :selected="$application->programme()?->id"
                                          :options="$application->choices->mapWithKeys(fn ($c) => [$c->programme_id => $c->programme->name])->all()" />

                                <x-textarea name="conditions" label="Conditions of admission" rows="2"
                                            hint="Optional. Printed on the letter."></x-textarea>

                                <x-input name="reporting_date" type="date" label="Reporting date"
                                         :value="$application->intake?->start_date?->toDateString()" />

                                <label class="flex items-start gap-2 text-xs text-slate-700">
                                    <input type="checkbox" name="confirm" value="1"
                                           class="mt-0.5 h-4 w-4 rounded border-slate-300 text-brand-700 focus:ring-brand-700">
                                    I confirm this admission decision.
                                </label>

                                <x-button type="submit" class="w-full">Admit &amp; generate letter</x-button>
                            </form>
                        </x-card>
                    @endif
                @endpermission

                @if ($application->admissionRecord)
                    <x-card class="border-emerald-200 bg-emerald-50">
                        <h2 class="text-sm font-semibold uppercase tracking-wider text-slate-900">Admitted</h2>
                        <p class="mt-3 font-mono text-sm font-semibold text-slate-900">
                            {{ $application->admissionRecord->admission_number }}
                        </p>
                        <p class="mt-1 text-xs text-slate-600">
                            {{ $application->admissionRecord->admitted_at->format('j F Y') }}
                        </p>

                        @permission('admissions.generate')
                            <div class="mt-4 space-y-2">
                                <x-button :href="route('admin.admissions.letter', $application->admissionRecord)"
                                          variant="outline" class="w-full">Download letter</x-button>

                                <form method="POST" action="{{ route('admin.admissions.regenerate', $application->admissionRecord) }}">
                                    @csrf
                                    <x-button type="submit" variant="ghost" class="w-full">Regenerate documents</x-button>
                                </form>
                            </div>
                        @endpermission
                    </x-card>
                @endif

                <x-card>
                    <h2 class="text-sm font-semibold uppercase tracking-wider text-slate-900">Request information</h2>
                    <p class="mt-2 text-xs text-slate-600">Sends the applicant a message and pauses the review.</p>

                    <form method="POST" action="{{ route('admin.applications.request-information', $application) }}" class="mt-4 space-y-3">
                        @csrf
                        <x-textarea name="message" label="What do you need?" rows="3" required></x-textarea>
                        <x-button type="submit" variant="outline" class="w-full">Send request</x-button>
                    </form>
                </x-card>

                @permission('applications.assign')
                    <x-card>
                        <h2 class="text-sm font-semibold uppercase tracking-wider text-slate-900">Reviewer</h2>

                        <form method="POST" action="{{ route('admin.applications.assign', $application) }}" class="mt-4 space-y-3">
                            @csrf
                            <x-select name="assigned_to" label="Assigned to" placeholder="Unassigned"
                                      :selected="$application->assigned_to"
                                      :options="$reviewers->pluck('name', 'id')->all()" />
                            <x-button type="submit" variant="outline" class="w-full">Save</x-button>
                        </form>
                    </x-card>
                @endpermission

                {{-- Notes --}}
                <x-card>
                    <h2 class="text-sm font-semibold uppercase tracking-wider text-slate-900">Notes</h2>

                    <form method="POST" action="{{ route('admin.applications.notes.store', $application) }}" class="mt-4 space-y-3">
                        @csrf
                        <x-textarea name="note" label="Add a note" rows="3" required></x-textarea>

                        <x-select name="visibility" label="Visibility"
                                  :options="['internal' => 'Internal only', 'applicant' => 'Visible to applicant']" />

                        <x-button type="submit" variant="outline" class="w-full">Add note</x-button>
                    </form>

                    @if ($application->notes->isNotEmpty())
                        <ul class="mt-5 space-y-3 border-t border-slate-100 pt-4">
                            @foreach ($application->notes as $note)
                                <li class="text-sm">
                                    <p class="text-slate-700">{{ $note->note }}</p>
                                    <p class="mt-1 flex flex-wrap items-center gap-2 text-xs text-slate-400">
                                        <span>{{ $note->author?->name ?? 'System' }}</span>
                                        <span>&middot;</span>
                                        <span>{{ $note->created_at->format('j M Y') }}</span>
                                        @if ($note->visibility === \App\Enums\NoteVisibility::Applicant)
                                            <x-badge color="amber" size="sm">Applicant sees this</x-badge>
                                        @endif
                                    </p>
                                </li>
                            @endforeach
                        </ul>
                    @endif
                </x-card>
            @endpermission
        </aside>
    </div>

@endsection
