<?php

namespace App\Http\Controllers\Care;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Care\Concerns\ScopesToAccount;
use App\Models\CareUnit;
use App\Models\Visit;
use App\Models\WardHandover;
use App\Services\Care\CarePermissions;
use App\Services\Care\NursingDocumentationService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Illuminate\View\View;

class NursingDocumentationController extends Controller
{
    use ScopesToAccount;

    public function unitNotes(Request $request, CareUnit $careUnit, NursingDocumentationService $docs): View
    {
        $this->authorizeAbility($request, 'nursing.notes.view');
        $this->authorizeOwner($request, $careUnit);
        abort_unless((int) $careUnit->organization_id === (int) $this->organization($request)->id, 404);

        $placedVisits = Visit::owned($this->ownerRef($request))
            ->where('care_unit_id', $careUnit->id)
            ->whereIn('status', [Visit::STATUS_OPEN, Visit::STATUS_IN_PROGRESS])
            ->with(['patient', 'bed'])
            ->orderBy('placed_at')
            ->get();

        return view('care.nursing.notes', [
            'unit' => $careUnit->load('department.branch'),
            'notes' => $docs->notesForUnit($careUnit, $this->ownerRef($request)),
            'placedVisits' => $placedVisits,
            'canWrite' => app(CarePermissions::class)->can($this->member($request), 'nursing.notes.manage'),
            'noteTypes' => config('care.nursing_note_types'),
            'shiftCodes' => config('care.staff_shift_codes'),
        ]);
    }

    public function storeNote(Request $request, CareUnit $careUnit, NursingDocumentationService $docs): RedirectResponse
    {
        $this->authorizeAbility($request, 'nursing.notes.manage');
        $this->authorizeOwner($request, $careUnit);

        $validated = $request->validate([
            'visit_id' => ['required', 'integer', 'exists:care_visits,id'],
            'note_type' => ['required', 'string', Rule::in(array_keys(config('care.nursing_note_types')))],
            'shift_code' => ['nullable', 'string', Rule::in(array_keys(config('care.staff_shift_codes')))],
            'body' => ['required', 'string', 'max:5000'],
        ]);

        $visit = Visit::owned($this->ownerRef($request))
            ->where('organization_id', $this->organization($request)->id)
            ->findOrFail($validated['visit_id']);
        $this->authorizeBranch($request, (int) $visit->branch_id);

        $docs->addNote(
            $visit,
            $this->ownerRef($request),
            $this->actorRef($request),
            $validated['body'],
            $validated['note_type'],
            $validated['shift_code'] ?? null,
            $careUnit->id,
        );

        return redirect()
            ->route('care.care-units.notes', $careUnit)
            ->with('success', 'Nursing note saved.');
    }

    public function handovers(Request $request, CareUnit $careUnit): View
    {
        $this->authorizeAbility($request, 'nursing.handover.view');
        $this->authorizeOwner($request, $careUnit);
        abort_unless((int) $careUnit->organization_id === (int) $this->organization($request)->id, 404);

        $handovers = WardHandover::owned($this->ownerRef($request))
            ->where('care_unit_id', $careUnit->id)
            ->orderByDesc('created_at')
            ->limit(30)
            ->get();

        return view('care.nursing.handovers', [
            'unit' => $careUnit->load('department.branch'),
            'handovers' => $handovers,
            'canWrite' => app(CarePermissions::class)->can($this->member($request), 'nursing.handover.manage'),
            'shiftCodes' => config('care.staff_shift_codes'),
            'statuses' => config('care.ward_handover_statuses'),
        ]);
    }

    public function createHandover(Request $request, CareUnit $careUnit, NursingDocumentationService $docs): View
    {
        $this->authorizeAbility($request, 'nursing.handover.manage');
        $this->authorizeOwner($request, $careUnit);

        return view('care.nursing.handover-form', [
            'unit' => $careUnit->load('department.branch'),
            'handover' => null,
            'patientSummaries' => $docs->defaultPatientSummaries($careUnit, $this->ownerRef($request)),
            'shiftCodes' => config('care.staff_shift_codes'),
        ]);
    }

    public function storeHandover(Request $request, CareUnit $careUnit, NursingDocumentationService $docs): RedirectResponse
    {
        $this->authorizeAbility($request, 'nursing.handover.manage');
        $this->authorizeOwner($request, $careUnit);

        $validated = $this->validatedHandover($request);
        $complete = $request->boolean('complete');

        $handover = $docs->createHandover(
            $careUnit,
            $this->ownerRef($request),
            $this->actorRef($request),
            $validated,
            $complete,
        );

        return redirect()
            ->route('care.care-units.handovers', $careUnit)
            ->with('success', $complete ? 'Handover completed.' : 'Handover draft saved.');
    }

    public function showHandover(Request $request, CareUnit $careUnit, WardHandover $wardHandover): View
    {
        $this->authorizeAbility($request, 'nursing.handover.view');
        $this->authorizeOwner($request, $careUnit);
        $this->authorizeOwner($request, $wardHandover);
        abort_unless((int) $wardHandover->care_unit_id === (int) $careUnit->id, 404);

        return view('care.nursing.handover-show', [
            'unit' => $careUnit->load('department.branch'),
            'handover' => $wardHandover,
            'shiftCodes' => config('care.staff_shift_codes'),
            'statuses' => config('care.ward_handover_statuses'),
            'canWrite' => app(CarePermissions::class)->can($this->member($request), 'nursing.handover.manage')
                && $wardHandover->status === WardHandover::STATUS_DRAFT,
        ]);
    }

    public function completeHandover(
        Request $request,
        CareUnit $careUnit,
        WardHandover $wardHandover,
        NursingDocumentationService $docs,
    ): RedirectResponse {
        $this->authorizeAbility($request, 'nursing.handover.manage');
        $this->authorizeOwner($request, $careUnit);
        $this->authorizeOwner($request, $wardHandover);
        abort_unless((int) $wardHandover->care_unit_id === (int) $careUnit->id, 404);

        $validated = $this->validatedHandover($request);
        $docs->completeHandover($wardHandover, $this->ownerRef($request), $this->actorRef($request), $validated);

        return redirect()
            ->route('care.care-units.handovers', $careUnit)
            ->with('success', 'Handover completed.');
    }

    /**
     * @return array<string, mixed>
     */
    protected function validatedHandover(Request $request): array
    {
        $validated = $request->validate([
            'from_shift' => ['nullable', 'string', Rule::in(array_keys(config('care.staff_shift_codes')))],
            'to_shift' => ['nullable', 'string', Rule::in(array_keys(config('care.staff_shift_codes')))],
            'received_by' => ['nullable', 'string', 'max:255'],
            'situation' => ['nullable', 'string', 'max:5000'],
            'background' => ['nullable', 'string', 'max:5000'],
            'assessment' => ['nullable', 'string', 'max:5000'],
            'recommendation' => ['nullable', 'string', 'max:5000'],
            'patient_summaries' => ['nullable', 'array'],
            'patient_summaries.*.visit_id' => ['nullable', 'integer'],
            'patient_summaries.*.patient_name' => ['nullable', 'string', 'max:255'],
            'patient_summaries.*.bed' => ['nullable', 'string', 'max:100'],
            'patient_summaries.*.note' => ['nullable', 'string', 'max:2000'],
        ]);

        return $validated;
    }
}
