<?php

namespace App\Livewire\Projects;

use App\Models\Feature;
use App\Models\FeatureType;
use App\Models\Layer;
use App\Models\Project;
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 ProjectFeaturesTable extends DataTableComponent
{
    protected $model = Feature::class;

    public int $projectId;

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

    #[On('features-changed')]
    public function refreshRows(): void
    {
        //
    }

    private function canManage(): bool
    {
        $user = Auth::user();

        return $user->can('manage all') ||
            ($user->can('edit layers') &&
                Project::whereKey($this->projectId)->whereHas('users', fn ($q) => $q->where('user_id', $user->id))->exists());
    }

    public function builder(): Builder
    {
        abort_unless($this->canManage(), 403);

        return Feature::query()
            ->whereHas('layer.phase', fn ($q) => $q->where('project_id', $this->projectId))
            ->with(['layer.phase', 'featureType']);
    }

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

            Column::make('Capa')
                ->secondaryHeaderFilter('layer')
                ->label(fn ($row) => e($row->layer?->name ?? '—')),

            Column::make('Fase')
                ->label(fn ($row) => e($row->layer?->phase?->name ?? '—')),

            Column::make('Tipo')
                ->secondaryHeaderFilter('type')
                ->label(fn ($row) => $row->featureType
                    ? '<span class="badge badge-sm" style="background-color:'.e($row->featureType->color).';color:#fff;border:0;">'.e($row->featureType->name).'</span>'
                    : '<span class="text-base-content/30 text-xs">—</span>')
                ->html(),

            Column::make('Activo', 'is_active')
                ->sortable()
                ->label(function ($row) {
                    if ($row->is_active) {
                        return '<button wire:click="toggleActive('.$row->id.')" class="badge badge-success badge-sm" title="Desactivar">Activo</button>';
                    }

                    return '<button wire:click="toggleActive('.$row->id.')" class="badge badge-ghost badge-sm" title="Activar">Inactivo</button>';
                })
                ->html(),

            Column::make('Acciones')
                ->label(fn ($row) => '<div class="flex justify-end gap-1">
                          <button wire:click="$dispatch(\'feature-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="deleteFeature('.$row->id.')" wire:confirm="¿Eliminar el elemento \''.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
    {
        $types = FeatureType::orderBy('name')->pluck('name', 'id')->toArray();

        return [
            TextFilter::make('Elemento', 'name')
                ->filter(fn (Builder $q, string $v) => $q->where('features.name', 'like', '%'.$v.'%')),

            SelectFilter::make('Capa', 'layer')
                ->options(['' => 'Todas'] + Layer::whereHas('phase', fn ($q) => $q->where('project_id', $this->projectId))->orderBy('name')->pluck('name', 'id')->toArray())
                ->filter(fn (Builder $q, string $v) => $q->where('features.layer_id', $v)),

            SelectFilter::make('Tipo', 'type')
                ->options(['' => 'Todos'] + $types)
                ->filter(fn (Builder $q, string $v) => $q->where('features.feature_type_id', $v)),
        ];
    }

    public function toggleActive(int $id): void
    {
        abort_unless($this->canManage(), 403);
        $feature = $this->findFeature($id);
        $feature->update(['is_active' => ! $feature->is_active]);
        $this->dispatch('features-changed');
        $this->dispatch('notify', $feature->is_active ? 'Elemento activado' : 'Elemento desactivado');
    }

    public function deleteFeature(int $id): void
    {
        abort_unless($this->canManage(), 403);
        $this->findFeature($id)->delete();
        $this->dispatch('features-changed');
        $this->dispatch('notify', 'Elemento eliminado');
    }

    private function findFeature(int $id): Feature
    {
        return Feature::whereHas('layer.phase', fn ($q) => $q->where('project_id', $this->projectId))->findOrFail($id);
    }
}
