<?php

namespace App\Livewire\Projects;

use App\Models\FeatureType;
use Illuminate\Support\Facades\Auth;
use Livewire\Attributes\Layout;
use Livewire\Component;

#[Layout('layouts.app')]
class FeatureTypeManager extends Component
{
    public $types = [];

    public bool $showForm = false;

    public $editingId = null;

    public string $name = '';

    public string $description = '';

    public string $color = '#6b7280';

    public function mount()
    {
        abort_unless(Auth::user()->can('edit layers'), 403);
        $this->loadTypes();
    }

    public function loadTypes(): void
    {
        $this->types = FeatureType::withCount('features')->orderBy('name')->get();
    }

    protected function rules(): array
    {
        return [
            'name' => 'required|string|max:255|unique:feature_types,name,'.($this->editingId ?? 'NULL'),
            'description' => 'nullable|string|max:255',
            'color' => 'required|string|max:7',
        ];
    }

    public function newType(): void
    {
        $this->reset(['editingId', 'name', 'description']);
        $this->color = '#6b7280';
        $this->resetErrorBag();
        $this->showForm = true;
    }

    public function edit($id): void
    {
        $t = FeatureType::findOrFail($id);
        $this->editingId = $t->id;
        $this->name = $t->name;
        $this->description = $t->description ?? '';
        $this->color = $t->color ?? '#6b7280';
        $this->resetErrorBag();
        $this->showForm = true;
    }

    public function save(): void
    {
        abort_unless(Auth::user()->can('edit layers'), 403);
        $this->validate();

        FeatureType::updateOrCreate(
            ['id' => $this->editingId],
            ['name' => $this->name, 'description' => $this->description ?: null, 'color' => $this->color],
        );

        $this->showForm = false;
        $this->loadTypes();
        $this->dispatch('notify', 'Tipo de elemento guardado');
    }

    public function delete($id): void
    {
        abort_unless(Auth::user()->can('edit layers'), 403);
        FeatureType::findOrFail($id)->delete();
        $this->loadTypes();
        $this->dispatch('notify', 'Tipo de elemento eliminado');
    }

    public function render()
    {
        return view('livewire.projects.feature-type-manager');
    }
}
