<?php

namespace App\Http\Controllers\Care;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Care\Concerns\ScopesToAccount;
use App\Models\Drug;
use App\Services\Care\AdminOverviewService;
use App\Services\Care\CarePermissions;
use App\Services\Care\OrganizationResolver;
use App\Services\Care\PharmacyService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class DrugController extends Controller
{
    use ScopesToAccount;

    public function __construct(
        protected PharmacyService $pharmacy,
        protected AdminOverviewService $adminOverview,
    ) {}

    public function index(Request $request): View
    {
        $this->authorizeAbility($request, 'pharmacy.view');
        $organization = $this->organization($request);
        $member = $this->member($request);
        $branchScope = app(OrganizationResolver::class)->branchScope($member);
        $permissions = app(CarePermissions::class);

        if ($permissions->isAdmin($member) && $request->query('view') !== 'list') {
            return view('care.admin.analytics', [
                'title' => 'Inventory',
                'badge' => 'Analytics · Stock health',
                'description' => 'Stock value, reorder risk, and expiry exposure across the pharmacy catalog.',
                'adminOverview' => $this->adminOverview->inventory(
                    $organization,
                    $this->ownerRef($request),
                    $branchScope,
                ),
            ]);
        }

        $drugs = $this->pharmacy->listDrugs(
            $this->ownerRef($request),
            $organization->id,
            $request->only(['q']),
            $branchScope,
        );

        $lowStock = $this->pharmacy->lowStock($this->ownerRef($request), $organization->id);
        $expired = $this->pharmacy->expiredBatches($this->ownerRef($request), $organization->id);

        $drugQuery = Drug::owned($this->ownerRef($request))
            ->where('organization_id', $organization->id)
            ->when($branchScope, fn ($q) => $q->where('branch_id', $branchScope));

        $heroStats = [
            'total' => (clone $drugQuery)->count(),
            'low_stock' => $lowStock->count(),
            'expired' => $expired->count(),
        ];

        return view('care.pharmacy.drugs.index', [
            'organization' => $organization,
            'drugs' => $drugs,
            'lowStock' => $lowStock,
            'expired' => $expired,
            'canManage' => $permissions->can($member, 'pharmacy.manage'),
            'heroStats' => $heroStats,
        ]);
    }

    public function create(Request $request): View
    {
        $this->authorizeAbility($request, 'pharmacy.manage');

        return view('care.pharmacy.drugs.create', [
            'organization' => $this->organization($request),
        ]);
    }

    public function store(Request $request): RedirectResponse
    {
        $this->authorizeAbility($request, 'pharmacy.manage');

        $drug = $this->pharmacy->createDrug(
            $this->organization($request),
            $this->ownerRef($request),
            $this->validatedDrugData($request),
        );

        return redirect()->route('care.pharmacy.drugs.show', $drug)
            ->with('success', 'Drug added to inventory.');
    }

    public function show(Request $request, Drug $drug): View
    {
        $this->authorizeAbility($request, 'pharmacy.view');
        $this->authorizeDrug($request, $drug);

        $drug->load(['batches' => fn ($q) => $q->orderBy('expiry_date')]);

        return view('care.pharmacy.drugs.show', [
            'drug' => $drug,
            'canManage' => app(\App\Services\Care\CarePermissions::class)
                ->can($this->member($request), 'pharmacy.manage'),
        ]);
    }

    public function edit(Request $request, Drug $drug): View
    {
        $this->authorizeAbility($request, 'pharmacy.manage');
        $this->authorizeDrug($request, $drug);

        return view('care.pharmacy.drugs.edit', ['drug' => $drug]);
    }

    public function update(Request $request, Drug $drug): RedirectResponse
    {
        $this->authorizeAbility($request, 'pharmacy.manage');
        $this->authorizeDrug($request, $drug);

        $this->pharmacy->updateDrug($drug, $this->ownerRef($request), $this->validatedDrugData($request));

        return redirect()->route('care.pharmacy.drugs.show', $drug)
            ->with('success', 'Drug updated.');
    }

    public function receiveBatch(Request $request, Drug $drug): RedirectResponse
    {
        $this->authorizeAbility($request, 'pharmacy.manage');
        $this->authorizeDrug($request, $drug);

        $this->pharmacy->receiveBatch(
            $drug,
            $this->ownerRef($request),
            $request->validate([
                'batch_number' => ['required', 'string', 'max:100'],
                'expiry_date' => ['nullable', 'date', 'after:today'],
                'quantity_on_hand' => ['required', 'integer', 'min:1'],
                'cost_minor' => ['nullable', 'integer', 'min:0'],
            ]),
            $this->ownerRef($request),
        );

        return back()->with('success', 'Stock received.');
    }

    protected function authorizeDrug(Request $request, Drug $drug): void
    {
        $this->authorizeOwner($request, $drug);
        abort_unless($drug->organization_id === $this->organization($request)->id, 404);
    }

    /**
     * @return array<string, mixed>
     */
    protected function validatedDrugData(Request $request): array
    {
        return $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'generic_name' => ['nullable', 'string', 'max:255'],
            'sku' => ['nullable', 'string', 'max:100'],
            'unit' => ['nullable', 'string', 'max:50'],
            'unit_price_minor' => ['nullable', 'integer', 'min:0'],
            'reorder_level' => ['nullable', 'integer', 'min:0'],
            'is_active' => ['nullable', 'boolean'],
        ]);
    }
}
