<?php

namespace App\Livewire;

use App\Models\Park;
use App\Models\ParkArea;
use Livewire\Component;
use Livewire\WithPagination;
use Illuminate\Contracts\Database\Eloquent\Builder;

class ParkAreaListComponent extends Component
{
    use WithPagination;

    public Park $park;
    public string $search = '';
    public string $sort = 'name';
    public string $direction = 'asc';
    public bool $showClosed = false;

    /** @var array<string, string> */
    public array $sortOptions = [
        'name' => 'Name',
        'opening_date' => 'Opening Date',
    ];

    protected $queryString = [
        'search' => ['except' => ''],
        'sort' => ['except' => 'name'],
        'direction' => ['except' => 'asc'],
        'showClosed' => ['except' => false],
    ];

    public function mount(Park $park): void
    {
        $this->park = $park;
        $this->resetPage('areas-page');
    }

    public function updatedSearch(): void
    {
        $this->resetPage('areas-page');
    }

    public function updatedShowClosed(): void
    {
        $this->resetPage('areas-page');
    }

    public function sortBy(string $field): void
    {
        if ($this->sort === $field) {
            $this->direction = $this->direction === 'asc' ? 'desc' : 'asc';
        } else {
            $this->sort = $field;
            $this->direction = 'asc';
        }
    }

    public function deleteArea(ParkArea $area): void
    {
        $area->delete();
        session()->flash('message', 'Area deleted successfully.');
    }

    public function render()
    {
        $query = $this->park->areas()
            ->when($this->search, function (Builder $query) {
                $query->where('name', 'like', '%' . $this->search . '%')
                    ->orWhere('description', 'like', '%' . $this->search . '%');
            })
            ->when(!$this->showClosed, function (Builder $query) {
                $query->whereNull('closing_date');
            })
            ->when($this->sort === 'name', function (Builder $query) {
                $query->orderBy('name', $this->direction);
            })
            ->when($this->sort === 'opening_date', function (Builder $query) {
                $query->orderBy('opening_date', $this->direction)
                    ->orderBy('name', 'asc');
            });

        return view('livewire.park-area-list-component', [
            'areas' => $query->paginate(10, pageName: 'areas-page'),
        ]);
    }
}