<?php

namespace App\Components\Workboard;

use App\Facades\Workboard;
use App\Models\WorkboardCategory;
use App\Services\HistoryService;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Component;

class WorkboardCategoryManager extends Component
{
    use AuthorizesRequests;

    public $categories;

    // Form
    public ?int $categoryId = null;
    public string $name = '';
    public string $description = '';
    public bool $isEditing = false;

    protected $rules = [
        'name'        => 'required|string|max:255',
        'description' => 'nullable|string',
    ];

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

    public function loadCategories(): void
    {
        $this->categories = WorkboardCategory::withCount('items')->latest()->get();
    }

    public function save(HistoryService $history): void
    {
        $this->authorize('workboard.manage');
        $this->validate();

        $wasEditing = (bool) $this->categoryId;

        if ($wasEditing) {
            $category = WorkboardCategory::findOrFail($this->categoryId);
            Workboard::updateCategory($category, [
                'name'        => $this->name,
                'description' => $this->description,
            ]);
            $history->add(auth()->user(), "Updated workboard category '{$this->name}'");
        } else {
            Workboard::createCategory([
                'name'        => $this->name,
                'description' => $this->description,
            ]);
            $history->add(auth()->user(), "Created workboard category '{$this->name}'");
        }

        $this->resetForm();
        $this->loadCategories();

        $this->dispatch('toast', type: 'success', message: $wasEditing ? 'Category updated.' : 'Category created.');
    }

    public function edit(int $id): void
    {
        $category = WorkboardCategory::findOrFail($id);
        $this->categoryId  = $category->id;
        $this->name        = $category->name;
        $this->description = $category->description ?? '';
        $this->isEditing   = true;
    }

    public function delete(HistoryService $history, int $id): void
    {
        $this->authorize('workboard.manage');
        $category = WorkboardCategory::withCount('items')->findOrFail($id);

        if ($category->items_count > 0) {
            $this->dispatch('toast', type: 'error', message: 'Cannot delete a category that still has items. Remove all items first.');
            return;
        }

        $name = $category->name;
        $category->delete();
        $history->add(auth()->user(), "Deleted workboard category '{$name}'");

        $this->loadCategories();
        $this->dispatch('toast', type: 'success', message: 'Category deleted.');
    }

    public function resetForm(): void
    {
        $this->reset(['categoryId', 'name', 'description', 'isEditing']);
    }

    public function render()
    {
        return view('components.workboard.workboard-category-manager');
    }
}
