<?php

namespace App\Livewire\Projects;

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

#[Layout('layouts.app')]
class ProjectTemplatesPicker extends Component
{
    public Project $project;

    public array $assignedIds = [];

    public string $search = '';

    public function mount(Project $project)
    {
        $this->project = $project;
        abort_unless(Auth::user()->can('edit projects'), 403);
        $this->assignedIds = $project->inspectionTemplates()->pluck('inspection_templates.id')->map(fn ($v) => (int) $v)->all();
    }

    public function toggle(int $templateId): void
    {
        abort_unless(Auth::user()->can('edit projects'), 403);
        InspectionTemplate::findOrFail($templateId); // valida

        if (in_array($templateId, $this->assignedIds, true)) {
            $this->project->inspectionTemplates()->detach($templateId);
            $this->assignedIds = array_values(array_diff($this->assignedIds, [$templateId]));
            $this->dispatch('notify', 'Plantilla desasignada del proyecto');
        } else {
            $this->project->inspectionTemplates()->syncWithoutDetaching([$templateId]);
            $this->assignedIds[] = $templateId;
            $this->dispatch('notify', 'Plantilla asignada al proyecto');
        }
    }

    public function render()
    {
        $templates = InspectionTemplate::query()
            ->when($this->search !== '', fn ($q) => $q->where('name', 'like', '%'.$this->search.'%'))
            ->orderBy('name')->get();

        return view('livewire.projects.project-templates-picker', [
            'templates' => $templates,
        ]);
    }
}
