<?php

namespace App\Components\Tag;

use App\Models\Tag;
use App\Services\HistoryService;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Support\Str;
use Livewire\Component;

class TagManager extends Component {
    use AuthorizesRequests;
    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(HistoryService $historyService) {
        $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:#',
        ]);

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

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

        $historyService->add(
            auth()->user(),
            $wasEditing ? "Updated Tag '{$this->name}'" : "Created Tag '{$this->name}'"
        );

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

        $this->dispatch('toast', type: 'success', message: $wasEditing ? '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(HistoryService $historyService, $id) {
        $this->authorize('tags.delete');
        $tag = Tag::findOrFail($id);
        $name = $tag->name;
        $tag->delete();

        $historyService->add(auth()->user(), "Deleted Tag '{$name}'");

        $this->loadTags();

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

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