<?php

namespace App\Components\Tag;

use App\Models\Tag;
use Illuminate\Support\Str;
use Livewire\Component;

class TagManager extends Component {
    public $tags;

    // Form properties
    public $tagId = null;
    public $name = '';
    public $description = '';
    public $color = '#3b82f6'; // Default blue

    public $isEditing = false;

    protected $rules = [
        'name' => 'required|string|max:255',
        'description' => 'nullable|string',
        'color' => 'required|string|size:7|starts_with:#',
    ];

    public function mount() {
        $this->authorize('tags.view');
        $this->loadTags();
    }

    public function loadTags() {
        $this->tags = Tag::latest()->get();
    }

    public function save() {
        $this->authorize($this->tagId ? 'tags.edit' : 'tags.create');
        $this->validate([
            'name' => 'required|string|max:255|unique:tags,name,' . $this->tagId,
            'description' => 'nullable|string',
            'color' => 'required|string|size:7|starts_with:#',
        ]);

        Tag::updateOrCreate(
            ['id' => $this->tagId],
            [
                'name' => $this->name,
                'slug' => Str::slug($this->name),
                'description' => $this->description,
                'color' => $this->color,
            ]
        );

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

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

    public function resetForm() {
        $this->reset(['tagId', 'name', 'description', 'color', 'isEditing']);
        $this->color = '#3b82f6';
    }

    public function edit($id) {
        $tag = Tag::findOrFail($id);
        $this->tagId = $tag->id;
        $this->name = $tag->name;
        $this->description = $tag->description;
        $this->color = $tag->color;
        $this->isEditing = true;
    }

    public function delete($id) {
        $this->authorize('tags.delete');
        Tag::findOrFail($id)->delete();
        $this->loadTags();

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

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