<?php

namespace Daylight\Core\Modules\MediaLibrary\Livewire;

use Daylight\Core\Modules\MediaLibrary\Services\MediaUploadService;
use Illuminate\Support\Facades\Log;
use Illuminate\View\View;
use Livewire\Attributes\On;
use Livewire\Component;
use Livewire\WithFileUploads;

class MediaUploader extends Component
{
    use WithFileUploads;

    public ?int $directoryId = null;

    public array $uploads = [];

    public bool $showModal = false;

    public array $uploadingFiles = [];

    public function mount(?int $directoryId = null): void
    {
        $this->directoryId = $directoryId;
    }

    #[On('open-upload-modal')]
    public function openModal(?int $directoryId = null): void
    {
        if ($directoryId !== null) {
            $this->directoryId = $directoryId;
        }
        $this->showModal = true;
        $this->uploadingFiles = [];
    }

    public function updatedUploads(): void
    {
        // This is called after Livewire finishes uploading files to temp storage
        $fileCount = is_array($this->uploads) ? count($this->uploads) : 0;

        if ($fileCount === 0) {
            return;
        }

        // Process each upload
        $this->processUploads();
    }

    protected function processUploads(): void
    {
        $uploadService = app(MediaUploadService::class);
        $this->uploadingFiles = [];

        foreach ($this->uploads as $index => $file) {
            // Update status to uploading
            $this->uploadingFiles[] = [
                'name' => $file->getClientOriginalName(),
                'size' => $file->getSize(),
                'status' => 'uploading',
                'error' => null,
            ];

            try {
                $media = $uploadService->upload($file, $this->directoryId);

                // Update status to success
                $this->uploadingFiles[$index]['status'] = 'success';

                $this->dispatch('file-uploaded', id: $media->id);
            } catch (\Exception $e) {
                Log::error('File upload failed: ' . $e->getMessage(), [
                    'file' => $file->getClientOriginalName(),
                    'directory_id' => $this->directoryId,
                    'error' => $e->getMessage(),
                ]);

                // Update status to error
                $this->uploadingFiles[$index]['status'] = 'error';
                $this->uploadingFiles[$index]['error'] = $e->getMessage();
            }
        }

        // Clear uploads after processing
        $this->uploads = [];

        // Check if all succeeded
        $hasErrors = collect($this->uploadingFiles)->contains('status', 'error');

        if (! $hasErrors) {
            $this->dispatch('uploads-complete');
        }
    }

    public function closeModalAfterUpload(): void
    {
        $this->showModal = false;
        $this->uploadingFiles = [];
    }

    public function closeModal(): void
    {
        $this->showModal = false;
        $this->uploads = [];
        $this->uploadingFiles = [];
    }

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