<?php

namespace App\Livewire;

use App\Enums\RideCategory;
use App\Models\Ride;
use Livewire\Component;
use Livewire\WithPagination;

class RideListComponent extends Component
{
    use WithPagination;

    /** @var string */
    public $search = '';

    /** @var string */
    public $category = '';

    /** @var string */
    public $sortField = 'name';

    /** @var string */
    public $sortDirection = 'asc';

    /** @var string */
    public $viewMode = 'grid';

    /**
     * Update search term and reset pagination.
     */
    public function updatingSearch(): void
    {
        $this->resetPage();
    }

    /**
     * Update category filter and reset pagination.
     */
    public function updatingCategory(): void
    {
        $this->resetPage();
    }

    /**
     * Sort results by the given field.
     */
    public function sortBy(string $field): void
    {
        if ($this->sortField === $field) {
            $this->sortDirection = $this->sortDirection === 'asc' ? 'desc' : 'asc';
        } else {
            $this->sortDirection = 'asc';
        }

        $this->sortField = $field;
    }

    /**
     * Toggle between grid and list views.
     */
    public function toggleView(): void
    {
        $this->viewMode = $this->viewMode === 'grid' ? 'list' : 'grid';
    }

    /**
     * Get all available ride categories.
     */
    public function getCategoriesProperty(): array
    {
        return RideCategory::options();
    }

    /**
     * Get the filtered and sorted rides query.
     */
    private function getRidesQuery()
    {
        return Ride::query()
            ->when($this->search, fn($query, $search) => 
                $query->where('name', 'like', "%{$search}%")
            )
            ->when($this->category, fn($query, $category) => 
                $query->where('category', $category)
            )
            ->orderBy($this->sortField, $this->sortDirection);
    }

    /**
     * Render the component.
     */
    public function render()
    {
        $rides = $this->getRidesQuery()->paginate(12);

        return view('livewire.ride-list', [
            'rides' => $rides,
        ]);
    }
}