<?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\BloodBank\BloodBankAnalyticsService;
use App\Services\Care\BloodBank\BloodBankWorkflowService;
use App\Services\Care\CarePermissions;
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 BloodBankWorkspaceController extends Controller
{
    use ScopesToAccount;

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

    protected function assertBloodBankManage(Request $request, SpecialtyModuleService $modules): void
    {
        $organization = $this->organization($request);
        abort_unless($modules->memberCanManage($organization, $this->member($request), 'blood_bank'), 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);
    }

    /**
     * Doctors use consultations.manage; Blood Bank managers use blood_bank.manage.
     */
    protected function authorizeBloodBankClinical(Request $request): void
    {
        $permissions = app(CarePermissions::class);
        $member = $this->member($request);
        abort_unless(
            $permissions->can($member, 'blood_bank.manage')
                || $permissions->can($member, 'consultations.manage'),
            403,
        );
    }

    protected function authorizeBloodBankViewAbility(Request $request): void
    {
        $permissions = app(CarePermissions::class);
        $member = $this->member($request);
        abort_unless(
            $permissions->can($member, 'blood_bank.view')
                || $permissions->can($member, 'blood_bank.manage')
                || $permissions->can($member, 'consultations.view')
                || $permissions->can($member, 'consultations.manage'),
            403,
        );
    }

    public function setStage(
        Request $request,
        Visit $visit,
        SpecialtyModuleService $modules,
        SpecialtyVisitStageService $stages,
        SpecialtyShellService $shell,
    ): RedirectResponse {
        $this->authorizeBloodBankClinical($request);
        $this->assertBloodBankManage($request, $modules);
        $this->assertVisit($request, $visit);

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

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

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

    public function confirmIssue(
        Request $request,
        Visit $visit,
        SpecialtyModuleService $modules,
        SpecialtyClinicalRecordService $clinical,
        SpecialtyVisitStageService $stages,
        SpecialtyShellService $shell,
        BloodBankWorkflowService $workflow,
    ): RedirectResponse {
        $this->authorizeBloodBankClinical($request);
        $this->assertBloodBankManage($request, $modules);
        $this->assertVisit($request, $visit);

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

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

        $validated = $request->validate(array_merge([
            'tab' => ['required', 'string'],
            'bill_product' => ['nullable', 'boolean'],
            'bill_crossmatch' => ['nullable', 'boolean'],
        ], $clinical->validationRules('blood_bank', 'issue_note')));

        $issuePayload = $clinical->payloadFromRequest($validated);
        $units = max(1, (int) ($issuePayload['units_issued'] ?? 1));

        $record = $clinical->upsert(
            $organization,
            $visit,
            'blood_bank',
            'issue_note',
            $issuePayload,
            $owner,
            $owner,
            BloodBankWorkflowService::STAGE_ISSUE,
            SpecialtyClinicalRecord::STATUS_COMPLETED,
        );

        // Keep the request record in sync with issued units / cross-match status.
        $requestRecord = $clinical->findForVisit($visit, 'blood_bank', 'blood_request');
        if ($requestRecord) {
            $requestPayload = array_merge($requestRecord->payload ?? [], [
                'issued_units' => $units,
                'crossmatch_status' => 'Issued',
                'product' => $issuePayload['product'] ?? ($requestRecord->payload['product'] ?? null),
            ]);
            $clinical->upsert(
                $organization,
                $visit,
                'blood_bank',
                'blood_request',
                $requestPayload,
                $owner,
                $owner,
                BloodBankWorkflowService::STAGE_ISSUE,
                SpecialtyClinicalRecord::STATUS_ACTIVE,
            );
        }

        try {
            $stages->setStage(
                $organization,
                $visit,
                'blood_bank',
                BloodBankWorkflowService::STAGE_ISSUE,
                $owner,
                $owner,
            );
        } catch (\InvalidArgumentException) {
            // Stage already issue or map empty.
        }

        if ($request->boolean('bill_crossmatch')) {
            try {
                $shell->addCatalogServiceToVisit($organization, $visit, 'blood_bank', 'bb.crossmatch', $owner, $owner);
            } catch (\InvalidArgumentException) {
            }
        }

        if ($request->boolean('bill_product', true)) {
            $serviceCode = $workflow->serviceCodeForProduct($issuePayload['product'] ?? null);
            if ($serviceCode) {
                try {
                    $shell->addCatalogServiceToVisit(
                        $organization,
                        $visit,
                        'blood_bank',
                        $serviceCode,
                        $owner,
                        $owner,
                        $units,
                    );
                } catch (\InvalidArgumentException) {
                }
            }
        }

        return redirect()
            ->route('care.specialty.workspace', ['module' => 'blood_bank', 'visit' => $visit, 'tab' => 'issue'])
            ->with('success', 'Product issue confirmed.');
    }

    public function saveTransfusion(
        Request $request,
        Visit $visit,
        SpecialtyModuleService $modules,
        SpecialtyClinicalRecordService $clinical,
        SpecialtyVisitStageService $stages,
        BloodBankWorkflowService $workflow,
    ): RedirectResponse {
        $this->authorizeBloodBankClinical($request);
        $this->assertBloodBankManage($request, $modules);
        $this->assertVisit($request, $visit);

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

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

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

        $record = $clinical->upsert(
            $organization,
            $visit,
            'blood_bank',
            'transfusion_note',
            $clinical->payloadFromRequest($validated),
            $owner,
            $owner,
            BloodBankWorkflowService::STAGE_TRANSFUSION,
            SpecialtyClinicalRecord::STATUS_COMPLETED,
        );

        try {
            $stages->setStage(
                $organization,
                $visit,
                'blood_bank',
                BloodBankWorkflowService::STAGE_TRANSFUSION,
                $owner,
                $owner,
            );
        } catch (\InvalidArgumentException) {
        }

        if ($workflow->shouldCompleteVisit($record->payload ?? [])) {
            try {
                $stages->setStage(
                    $organization,
                    $visit,
                    'blood_bank',
                    BloodBankWorkflowService::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' => 'blood_bank', 'visit' => $visit, 'tab' => 'transfusion'])
            ->with('success', 'Transfusion record saved.');
    }

    public function reports(
        Request $request,
        SpecialtyModuleService $modules,
        SpecialtyShellService $shell,
        BloodBankAnalyticsService $analytics,
    ): View {
        $this->authorizeBloodBankViewAbility($request);
        $this->assertBloodBankAccess($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.blood-bank.reports', [
            'moduleKey' => 'blood_bank',
            'definition' => $modules->definition('blood_bank'),
            'shellNav' => $shell->navItems('blood_bank'),
            '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->authorizeBloodBankViewAbility($request);
        $this->assertBloodBankAccess($request, $modules);
        $this->assertVisit($request, $visit);

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

        return view('care.specialty.blood-bank.print', [
            'visit' => $visit,
            'patient' => $visit->patient,
            'bloodRequest' => $clinical->findForVisit($visit, 'blood_bank', 'blood_request'),
            'inventoryNote' => $clinical->findForVisit($visit, 'blood_bank', 'inventory_note'),
            'issueNote' => $clinical->findForVisit($visit, 'blood_bank', 'issue_note'),
            'transfusionNote' => $clinical->findForVisit($visit, 'blood_bank', 'transfusion_note'),
        ]);
    }
}
