<?php

namespace Daylight\Core\Modules\MediaLibrary\Livewire;

use Daylight\Core\Modules\MediaLibrary\Models\Directory;
use Illuminate\View\View;
use Livewire\Attributes\On;
use Livewire\Component;

class DirectoryInfo extends Component
{
    public ?int $directoryId = null;

    public ?Directory $directory = null;

    public string $name = '';

    public function mount(?int $directoryId = null): void
    {
        $this->directoryId = $directoryId;
        $this->directory = $this->directoryId ? Directory::query()->find($this->directoryId) : null;
        $this->name = $this->directory?->name ?? '';
    }

    #[On('open-directory-info')]
    public function open(?int $id = null): void
    {
        if ($id) {
            $this->directoryId = $id;
        }

        $this->directory = $this->directoryId ? Directory::query()->find($this->directoryId) : null;
        $this->name = $this->directory?->name ?? '';
    }

    public function update(): void
    {
        $this->validate([
            'name' => ['required', 'string', 'max:255'],
        ]);

        if ($this->directory) {
            $this->directory->update(['name' => $this->name]);
        }

        $this->dispatch('directory-updated');
        $this->dispatch('close-directory-info');
    }

    public function delete(): void
    {
        if (! $this->directory) {
            return;
        }

        $parentId = $this->directory->parent_id;
        $this->directory->delete();

        $this->dispatch('directory-deleted', parentId: $parentId);
        $this->dispatch('close-directory-info');
    }

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