<?php

namespace Daylight\Core\Modules\MediaLibrary\Livewire;

use Daylight\Core\Modules\MediaLibrary\Models\Media as MediaModel;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\View\View;
use Livewire\Attributes\Computed;
use Livewire\Component;
use Livewire\WithPagination;

class FileGrid extends Component
{
    use WithPagination;

    public ?int $directoryId = null;

    public string $search = '';

    public bool $selectable = false;

    public bool $singleFile = false;

    public array $selectedItems = [];

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

    #[Computed]
    public function files(): LengthAwarePaginator
    {
        $query = MediaModel::query();

        if ($this->directoryId) {
            $query->where('directory_id', $this->directoryId);
        } else {
            $query->whereNull('directory_id');
        }

        if ($this->search) {
            $query->where('name', 'like', '%' . $this->search . '%');
        }

        return $query->latest()->paginate(40, pageName: 'media-page');
    }

    public function select(int $mediaId): void
    {
        $this->dispatch('select-file', id: $mediaId);
    }

    public function render(): View
    {
        return view('daylight::livewire.media.file-grid');
    }
}
