<?php

namespace App\Livewire\Inspections;

use App\Models\InspectionTemplate;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Auth;
use Livewire\Attributes\On;
use Rappasoft\LaravelLivewireTables\DataTableComponent;
use Rappasoft\LaravelLivewireTables\Views\Column;
use Rappasoft\LaravelLivewireTables\Views\Filters\SelectFilter;
use Rappasoft\LaravelLivewireTables\Views\Filters\TextFilter;

class InspectionTemplatesTable extends DataTableComponent
{
    protected $model = InspectionTemplate::class;

    public function configure(): void
    {
        $this->setPrimaryKey('id')
            ->setDefaultSort('inspection_templates.name', 'asc')
            ->setSortingPillsEnabled(false)
            ->setSecondaryHeaderEnabled()
            ->setAdditionalSelects([
                'inspection_templates.id as id',
                'inspection_templates.fields as fields',
            ]);
    }

    /** Refrescar cuando el manager crea/edita/borra. */
    #[On('templates-changed')]
    public function refreshRows(): void
    {
        //
    }

    public function builder(): Builder
    {
        abort_unless(Auth::user()->can('manage templates'), 403);

        return InspectionTemplate::query()
            ->withCount('projects');
    }

    public function columns(): array
    {
        return [
            Column::make('Plantilla', 'name')
                ->sortable()->searchable()
                ->secondaryHeaderFilter('name')
                ->format(fn ($value) => '<span class="font-medium">'.e($value).'</span>')
                ->html(),

            Column::make('Descripción', 'description')
                ->searchable()
                ->secondaryHeaderFilter('description')
                ->format(fn ($value) => $value
                    ? '<span class="text-sm text-base-content/70">'.e($value).'</span>'
                    : '<span class="text-base-content/30 text-xs">—</span>')
                ->html(),

            Column::make('Campos')
                ->label(fn ($row) => '<span class="badge badge-ghost badge-sm">'.count($row->fields ?? []).'</span>')
                ->html(),

            Column::make('Proyectos')
                ->secondaryHeaderFilter('usage')
                ->label(function ($row) {
                    $n = (int) ($row->projects_count ?? 0);
                    $cls = $n > 0 ? 'badge-info' : 'badge-ghost';

                    return '<span class="badge '.$cls.' badge-sm">'.$n.'</span>';
                })
                ->html(),

            Column::make('Acciones')
                ->label(fn ($row) => '<div class="flex justify-end gap-1">
                          <button wire:click="$dispatch(\'template-edit\', { id: '.$row->id.' })"
                                  class="btn btn-xs btn-ghost" title="Editar">
                              <svg xmlns="http://www.w3.org/2000/svg" class="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/></svg>
                          </button>
                          <button wire:click="$dispatch(\'template-delete\', { id: '.$row->id.' })"
                                  wire:confirm="¿Eliminar la plantilla \''.e($row->name).'\'? Esta acción no se puede deshacer."
                                  class="btn btn-xs btn-error btn-outline" title="Eliminar">
                              <svg xmlns="http://www.w3.org/2000/svg" class="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
                          </button>
                      </div>')
                ->html(),
        ];
    }

    public function filters(): array
    {
        return [
            TextFilter::make('Plantilla', 'name')
                ->config(['placeholder' => 'Buscar nombre…'])
                ->filter(fn (Builder $q, string $v) => $q->where('inspection_templates.name', 'like', '%'.$v.'%')),

            TextFilter::make('Descripción', 'description')
                ->config(['placeholder' => 'Buscar descripción…'])
                ->filter(fn (Builder $q, string $v) => $q->where('inspection_templates.description', 'like', '%'.$v.'%')),

            SelectFilter::make('Uso', 'usage')
                ->options(['' => 'Todos', 'used' => 'En uso (≥1 proyecto)', 'unused' => 'Sin uso'])
                ->filter(function (Builder $q, string $v) {
                    if ($v === 'used') {
                        $q->has('projects');
                    }
                    if ($v === 'unused') {
                        $q->doesntHave('projects');
                    }
                }),
        ];
    }
}
