<?php

namespace App\Livewire\Admin\Cms;

use FluxCms\Core\Services\MediaConversionService;
use Livewire\Component;
use Livewire\WithFileUploads;

class MediaLibraryUploader extends Component
{
    use WithFileUploads;

    /** @var array<\Livewire\Features\SupportFileUploads\TemporaryUploadedFile> */
    public array $uploads = [];

    public function updatedUploads(): void
    {
        $this->validate([
            'uploads' => 'nullable|array|max:20',
            'uploads.*' => 'file|mimes:jpeg,jpg,png,gif,webp,svg,pdf,doc,docx|max:10240',
        ]);

        $service = app(MediaConversionService::class);

        foreach ($this->uploads as $file) {
            $media = $service->storeUpload($file);
            $this->dispatch('media-library-uploaded', mediaId: $media->id);
        }

        $this->uploads = [];
    }

    public function removeUpload(int $index): void
    {
        if (isset($this->uploads[$index])) {
            unset($this->uploads[$index]);
            $this->uploads = array_values($this->uploads);
        }
    }

    public function render()
    {
        return view('livewire.admin.cms.media-library-uploader');
    }
}
