<?php

namespace App\Components\Workboard;

use App\Facades\Workboard;
use App\Models\WorkboardCategory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Component;

class WorkboardAssigner extends Component
{
    use AuthorizesRequests;

    public Model $model;

    // Form
    public ?int $categoryId = null;
    public string $title = '';
    public string $description = '';
    public string $due_at = '';

    public function mount(Model $model): void
    {
        $this->model = $model;
        // Pre-fill the title from the model if it has a name or title attribute
        $this->title = $model->title ?? $model->name ?? '';
    }

    public function getAvailableCategoriesProperty()
    {
        return WorkboardCategory::orderBy('name')->get();
    }

    public function addToWorkboard(): void
    {
        $this->authorize('workboard.manage');

        $this->validate([
            'categoryId'  => 'required|integer|exists:workboard_categories,id',
            'title'       => 'required|string|max:255',
            'description' => 'nullable|string|max:2000',
            'due_at'      => 'nullable|date',
        ]);

        $category = WorkboardCategory::findOrFail($this->categoryId);

        Workboard::addItem($category, [
            'title'       => $this->title,
            'description' => $this->description ?: null,
            'due_at'      => $this->due_at ?: null,
            'owner_type'  => get_class($this->model),
            'owner_id'    => $this->model->getKey(),
        ]);

        $this->reset(['categoryId', 'description', 'due_at']);
        $this->title = $this->model->title ?? $this->model->name ?? '';

        $this->dispatch('toast', type: 'success', message: 'Added to workboard queue.');
        $this->dispatch('close-workboard-assigner-modal-' . $this->model->getKey());
    }

    public function render()
    {
        return view('components.workboard.workboard-assigner', [
            'availableCategories' => $this->availableCategories,
        ]);
    }
}
