<?php

namespace App\Livewire;

use App\BioCabinet;
use App\BioRack;
use Livewire\Component;

class BiorepositoryVisual extends Component
{
    public ?int $selectedCabinetId = null;
    public ?int $selectedRackId = null;
    public ?int $selectedSlot = null;
    public ?int $selectedShelf = null;
    public ?int $selectedBox = null;

    public function mount(): void
    {
        $this->selectedCabinetId = BioCabinet::orderBy('name', 'ASC')->value('id');
    }

    public function selectCabinet(int $cabinetId): void
    {
        $this->selectedCabinetId = $cabinetId;
        $this->selectedRackId = null;
        $this->resetPosition();
    }

    public function selectRack(int $rackId): void
    {
        $this->selectedRackId = $rackId;
        $this->resetPosition();
    }

    public function selectSlot(int $slot): void
    {
        $this->selectedSlot = $slot;
        $this->selectedShelf = null;
        $this->selectedBox = null;
    }

    public function selectShelf(int $shelf): void
    {
        $this->selectedShelf = $shelf;
        $this->selectedBox = null;
    }

    public function selectBox(int $box): void
    {
        $this->selectedBox = $box;
    }

    public function render()
    {
        $cabinets = BioCabinet::withCount(['racks', 'specimens'])
            ->orderBy('name', 'ASC')
            ->get();

        if (!$this->selectedCabinetId && $cabinets->isNotEmpty()) {
            $this->selectedCabinetId = (int) $cabinets->first()->id;
        }

        $selectedCabinet = $this->selectedCabinetId
            ? BioCabinet::with([
                'racks' => function ($query) {
                    $query->withCount('specimens')
                        ->orderBy('rack_number', 'ASC')
                        ->orderBy('code', 'ASC');
                },
            ])->find($this->selectedCabinetId)
            : null;

        $selectedRack = $this->selectedRackId
            ? BioRack::with(['specimens' => function ($query) {
                $query->orderBy('slot_number', 'ASC')
                    ->orderBy('shelf_number', 'ASC')
                    ->orderBy('box_number', 'ASC')
                    ->orderBy('tube_number', 'ASC');
            }])->find($this->selectedRackId)
            : null;

        if ($selectedRack && (int) $selectedRack->cabinet_id !== (int) $this->selectedCabinetId) {
            $selectedRack = null;
            $this->selectedRackId = null;
            $this->resetPosition();
        }

        return view('livewire.biorepository-visual', [
            'cabinets' => $cabinets,
            'selectedCabinet' => $selectedCabinet,
            'selectedRack' => $selectedRack,
        ]);
    }

    private function resetPosition(): void
    {
        $this->selectedSlot = null;
        $this->selectedShelf = null;
        $this->selectedBox = null;
    }
}
