<?php

namespace App\Http\Controllers\Care;

use App\Http\Controllers\Care\Concerns\ScopesToAccount;
use App\Http\Controllers\Controller;
use App\Models\Appointment;
use App\Models\Branch;
use App\Models\Department;
use App\Models\Patient;
use App\Models\SpecialtyClinicalRecord;
use App\Models\Visit;
use App\Services\Care\Ambulance\AmbulanceAnalyticsService;
use App\Services\Care\Ambulance\AmbulanceWorkflowService;
use App\Services\Care\AppointmentService;
use App\Services\Care\AuditLogger;
use App\Services\Care\OrganizationResolver;
use App\Services\Care\SpecialtyClinicalRecordService;
use App\Services\Care\SpecialtyModuleService;
use App\Services\Care\SpecialtyShellService;
use App\Services\Care\SpecialtyVisitStageService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class AmbulanceWorkspaceController extends Controller
{
    use ScopesToAccount;

    protected function assertAmbulanceAccess(Request $request, SpecialtyModuleService $modules): void
    {
        $organization = $this->organization($request);
        abort_unless($modules->memberCanAccess($organization, $this->member($request), 'ambulance'), 403);
    }

    protected function assertAmbulanceManage(Request $request, SpecialtyModuleService $modules): void
    {
        $organization = $this->organization($request);
        abort_unless($modules->memberCanManage($organization, $this->member($request), 'ambulance'), 403);
    }

    protected function assertVisit(Request $request, Visit $visit): void
    {
        abort_unless($visit->organization_id === $this->organization($request)->id, 404);
        $this->authorizeBranch($request, (int) $visit->branch_id);
    }

    public function newCallCreate(
        Request $request,
        SpecialtyModuleService $modules,
    ): View {
        $this->authorizeAbility($request, 'ambulance.manage');
        $this->assertAmbulanceManage($request, $modules);

        $organization = $this->organization($request);
        $owner = $this->ownerRef($request);
        $member = $this->member($request);
        $branchScope = app(OrganizationResolver::class)->branchScope($member);

        $branches = Branch::owned($owner)
            ->where('organization_id', $organization->id)
            ->where('is_active', true)
            ->when($branchScope, fn ($q) => $q->where('id', $branchScope))
            ->orderBy('name')
            ->get();

        $defaultBranch = $branchScope ?? $branches->first()?->id;

        $patients = Patient::owned($owner)
            ->where('organization_id', $organization->id)
            ->when($branchScope, fn ($q) => $q->where('branch_id', $branchScope))
            ->orderBy('first_name')
            ->limit(200)
            ->get();

        return view('care.specialty.ambulance.new-call', [
            'organization' => $organization,
            'branches' => $branches,
            'defaultBranch' => $defaultBranch,
            'patients' => $patients,
        ]);
    }

    public function newCallStore(
        Request $request,
        SpecialtyModuleService $modules,
        AppointmentService $appointments,
    ): RedirectResponse {
        $this->authorizeAbility($request, 'ambulance.manage');
        $this->assertAmbulanceManage($request, $modules);

        $organization = $this->organization($request);
        $owner = $this->ownerRef($request);
        $member = $this->member($request);
        $branchScope = app(OrganizationResolver::class)->branchScope($member);

        $validated = $request->validate([
            'branch_id' => ['required', 'integer', 'exists:care_branches,id'],
            'patient_id' => ['required', 'integer', 'exists:care_patients,id'],
            'reason' => ['nullable', 'string', 'max:500'],
            'notes' => ['nullable', 'string', 'max:2000'],
            'location' => ['nullable', 'string', 'max:500'],
        ]);

        $branchId = (int) $validated['branch_id'];
        if ($branchScope !== null) {
            abort_unless($branchId === (int) $branchScope, 403);
        }
        $this->authorizeBranch($request, $branchId);

        $department = Department::owned($owner)
            ->where('type', 'ambulance')
            ->where('branch_id', $branchId)
            ->where('is_active', true)
            ->orderBy('id')
            ->first();

        if (! $department) {
            return back()->withInput()->with('error', 'No active ambulance department at this branch.');
        }

        $patient = Patient::owned($owner)
            ->where('organization_id', $organization->id)
            ->findOrFail((int) $validated['patient_id']);

        $reason = trim((string) ($validated['reason'] ?? ''));
        if ($reason === '') {
            $reason = 'Ambulance call';
        }
        if (! empty($validated['location'])) {
            $reason .= ' · '.$validated['location'];
        }

        $appointment = $appointments->walkIn($organization, $owner, [
            'patient_id' => $patient->id,
            'branch_id' => $branchId,
            'department_id' => $department->id,
            'reason' => $reason,
            'notes' => $validated['notes'] ?? null,
        ], $this->actorRef($request) ?? $owner);

        AuditLogger::record(
            $owner,
            'ambulance.new_call',
            $organization->id,
            $this->actorRef($request) ?? $owner,
            Appointment::class,
            $appointment->id,
            ['department_id' => $department->id],
        );

        return redirect()
            ->route('care.specialty.show', 'ambulance')
            ->with('success', 'New call logged for '.$patient->fullName().'.');
    }

    public function setStage(
        Request $request,
        Visit $visit,
        SpecialtyModuleService $modules,
        SpecialtyVisitStageService $stages,
        SpecialtyShellService $shell,
    ): RedirectResponse {
        $this->authorizeAbility($request, 'ambulance.manage');
        $this->assertAmbulanceManage($request, $modules);
        $this->assertVisit($request, $visit);

        $validated = $request->validate([
            'stage' => ['required', 'string', 'max:32'],
        ]);

        try {
            $stages->setStage(
                $this->organization($request),
                $visit,
                'ambulance',
                $validated['stage'],
                $this->ownerRef($request),
                $this->actorRef($request),
            );
        } catch (\InvalidArgumentException $e) {
            return back()->with('error', $e->getMessage());
        }

        return redirect()
            ->route('care.specialty.workspace', [
                'module' => 'ambulance',
                'visit' => $visit,
                'tab' => $shell->workspaceTabForStage('ambulance', $validated['stage']),
            ])
            ->with('success', 'Visit stage updated.');
    }

    public function saveHandover(
        Request $request,
        Visit $visit,
        SpecialtyModuleService $modules,
        SpecialtyClinicalRecordService $clinical,
        SpecialtyVisitStageService $stages,
        AmbulanceWorkflowService $workflow,
    ): RedirectResponse {
        $this->authorizeAbility($request, 'consultations.manage');
        $this->assertAmbulanceManage($request, $modules);
        $this->assertVisit($request, $visit);

        $organization = $this->organization($request);
        $owner = $this->ownerRef($request);

        $payload = (array) $request->input('payload', []);
        foreach ($clinical->fieldsFor('ambulance', 'amb_handover') as $field) {
            if (($field['type'] ?? '') === 'boolean') {
                $payload[$field['name']] = $request->boolean('payload.'.$field['name']);
            }
        }
        $request->merge(['payload' => $payload, 'tab' => 'handover']);

        $validated = $request->validate(array_merge([
            'tab' => ['required', 'string'],
        ], $clinical->validationRules('ambulance', 'amb_handover')));

        $record = $clinical->upsert(
            $organization,
            $visit,
            'ambulance',
            'amb_handover',
            $clinical->payloadFromRequest($validated),
            $owner,
            $owner,
            AmbulanceWorkflowService::STAGE_HANDOVER,
            SpecialtyClinicalRecord::STATUS_COMPLETED,
        );

        try {
            $stages->setStage(
                $organization,
                $visit,
                'ambulance',
                AmbulanceWorkflowService::STAGE_HANDOVER,
                $owner,
                $owner,
            );
        } catch (\InvalidArgumentException) {
        }

        if ($workflow->shouldCompleteVisit($record->payload ?? [])) {
            try {
                $stages->setStage(
                    $organization,
                    $visit,
                    'ambulance',
                    AmbulanceWorkflowService::STAGE_COMPLETED,
                    $owner,
                    $owner,
                );
            } catch (\InvalidArgumentException) {
            }

            $visit->refresh();
            if ($visit->status !== Visit::STATUS_COMPLETED) {
                $visit->update([
                    'status' => Visit::STATUS_COMPLETED,
                    'completed_at' => $visit->completed_at ?? now(),
                ]);
            }

            $appointment = $visit->appointment;
            if ($appointment && $appointment->status !== \App\Models\Appointment::STATUS_COMPLETED) {
                $appointment->update([
                    'status' => \App\Models\Appointment::STATUS_COMPLETED,
                    'completed_at' => $appointment->completed_at ?? now(),
                ]);
            }
        }

        return redirect()
            ->route('care.specialty.workspace', ['module' => 'ambulance', 'visit' => $visit, 'tab' => 'handover'])
            ->with('success', 'Handover saved.');
    }

    public function reports(
        Request $request,
        SpecialtyModuleService $modules,
        SpecialtyShellService $shell,
        AmbulanceAnalyticsService $analytics,
    ): View {
        $this->authorizeAbility($request, 'consultations.view');
        $this->assertAmbulanceAccess($request, $modules);

        $organization = $this->organization($request);
        $branchScope = app(\App\Services\Care\OrganizationResolver::class)->branchScope($this->member($request));

        $report = $analytics->report(
            $organization,
            $this->ownerRef($request),
            $branchScope,
            $request->query('from'),
            $request->query('to'),
        );

        return view('care.specialty.ambulance.reports', [
            'moduleKey' => 'ambulance',
            'definition' => $modules->definition('ambulance'),
            'shellNav' => $shell->navItems('ambulance'),
            'report' => $report,
            'currency' => strtoupper((string) config('care.billing.currency', config('care.currency', 'GHS'))),
        ]);
    }

    public function printSummary(
        Request $request,
        Visit $visit,
        SpecialtyModuleService $modules,
        SpecialtyClinicalRecordService $clinical,
    ): View {
        $this->authorizeAbility($request, 'consultations.view');
        $this->assertAmbulanceAccess($request, $modules);
        $this->assertVisit($request, $visit);

        $visit->loadMissing(['patient', 'appointment.practitioner', 'branch']);

        return view('care.specialty.ambulance.print', [
            'visit' => $visit,
            'patient' => $visit->patient,
            'dispatch' => $clinical->findForVisit($visit, 'ambulance', 'amb_dispatch'),
            'scene' => $clinical->findForVisit($visit, 'ambulance', 'amb_scene'),
            'enRoute' => $clinical->findForVisit($visit, 'ambulance', 'amb_en_route'),
            'handover' => $clinical->findForVisit($visit, 'ambulance', 'amb_handover'),
        ]);
    }
}
