<?php

namespace App\Http\Controllers\Care;

use App\Http\Controllers\Care\Concerns\ScopesToAccount;
use App\Http\Controllers\Controller;
use App\Models\SpecialtyClinicalRecord;
use App\Models\Visit;
use App\Services\Care\Emergency\EmergencyAnalyticsService;
use App\Services\Care\Emergency\EmergencyVitalsService;
use App\Services\Care\Emergency\EmergencyWorkflowService;
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 EmergencyWorkspaceController extends Controller
{
    use ScopesToAccount;

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

    protected function assertEmergencyManage(Request $request, SpecialtyModuleService $modules): void
    {
        $organization = $this->organization($request);
        abort_unless($modules->memberCanManage($organization, $this->member($request), 'emergency'), 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 setStage(
        Request $request,
        Visit $visit,
        SpecialtyModuleService $modules,
        SpecialtyVisitStageService $stages,
        SpecialtyShellService $shell,
    ): RedirectResponse {
        $this->authorizeAbility($request, 'consultations.manage');
        $this->assertEmergencyManage($request, $modules);
        $this->assertVisit($request, $visit);

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

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

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

    public function saveVitals(
        Request $request,
        Visit $visit,
        SpecialtyModuleService $modules,
        EmergencyVitalsService $vitals,
    ): RedirectResponse {
        $permissions = app(\App\Services\Care\CarePermissions::class);
        $member = $this->member($request);
        abort_unless(
            $permissions->can($member, 'vitals.manage')
            || $permissions->can($member, 'consultations.manage'),
            403,
        );
        $this->assertEmergencyManage($request, $modules);
        $this->assertVisit($request, $visit);

        $validated = $request->validate([
            'bp_systolic' => ['nullable', 'integer', 'min:0', 'max:300'],
            'bp_diastolic' => ['nullable', 'integer', 'min:0', 'max:200'],
            'pulse' => ['nullable', 'integer', 'min:0', 'max:300'],
            'temperature' => ['nullable', 'numeric', 'min:30', 'max:45'],
            'spo2' => ['nullable', 'integer', 'min:0', 'max:100'],
            'respiratory_rate' => ['nullable', 'integer', 'min:0', 'max:80'],
            'weight_kg' => ['nullable', 'numeric', 'min:0', 'max:500'],
            'height_cm' => ['nullable', 'numeric', 'min:0', 'max:300'],
        ]);

        try {
            $vitals->record(
                $this->organization($request),
                $visit,
                $this->ownerRef($request),
                $validated,
                $this->actorRef($request),
            );
        } catch (\InvalidArgumentException $e) {
            return back()->with('error', $e->getMessage());
        }

        return redirect()
            ->route('care.specialty.workspace', ['module' => 'emergency', 'visit' => $visit, 'tab' => 'vitals'])
            ->with('success', 'Vitals recorded.');
    }

    public function saveDisposition(
        Request $request,
        Visit $visit,
        SpecialtyModuleService $modules,
        SpecialtyClinicalRecordService $clinical,
        SpecialtyVisitStageService $stages,
        EmergencyWorkflowService $workflow,
    ): RedirectResponse {
        $this->authorizeAbility($request, 'emergency.discharge');
        $this->assertEmergencyManage($request, $modules);
        $this->assertVisit($request, $visit);

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

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

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

        $record = $clinical->upsert(
            $organization,
            $visit,
            'emergency',
            'disposition',
            $clinical->payloadFromRequest($validated),
            $owner,
            $owner,
            EmergencyWorkflowService::STAGE_DISPOSITION,
            SpecialtyClinicalRecord::STATUS_COMPLETED,
        );

        try {
            $stages->setStage(
                $organization,
                $visit,
                'emergency',
                EmergencyWorkflowService::STAGE_DISPOSITION,
                $owner,
                $owner,
            );
        } catch (\InvalidArgumentException) {
            // Stage already disposition or map empty.
        }

        if ($workflow->shouldCompleteVisit($record->payload ?? [])) {
            $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' => 'emergency', 'visit' => $visit, 'tab' => 'disposition'])
            ->with('success', 'Disposition saved.');
    }

    public function reports(
        Request $request,
        SpecialtyModuleService $modules,
        SpecialtyShellService $shell,
        EmergencyAnalyticsService $analytics,
    ): View {
        $this->authorizeAbility($request, 'consultations.view');
        $this->assertEmergencyAccess($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.emergency.reports', [
            'moduleKey' => 'emergency',
            'definition' => $modules->definition('emergency'),
            'shellNav' => $shell->navItems('emergency'),
            'report' => $report,
            'currency' => strtoupper((string) config('care.billing.currency', config('care.currency', 'GHS'))),
        ]);
    }

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

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

        return view('care.specialty.emergency.print', [
            'visit' => $visit,
            'patient' => $visit->patient,
            'triage' => $clinical->findForVisit($visit, 'emergency', 'triage'),
            'clinicalNote' => $clinical->findForVisit($visit, 'emergency', 'clinical_note'),
            'observation' => $clinical->findForVisit($visit, 'emergency', 'observation'),
            'disposition' => $clinical->findForVisit($visit, 'emergency', 'disposition'),
            'vitals' => $vitals->forVisit($visit),
            'latestVitals' => $vitals->latestForVisit($visit),
        ]);
    }
}
