<?php

namespace App\Livewire\LicenseTokens\Components;

use App\Models\Clients\Client;
use App\Models\Products\LicenseToken;
use Livewire\Component;
use Livewire\WithPagination;

class LicensesTable extends Component
{
    use WithPagination;

    public ?Client $client = null;
    public bool $showRadio = false;
    public bool $showActions = false;
    public bool $showClient = false;
    public ?string $selectedTokenIdProperty = 'selectedTokenId';
    public ?int $selectedTokenId = null;
    public string $search = '';

    protected $listeners = [
        'tokenSelected' => 'handleTokenSelected',
        'tokenDeleted' => 'handleTokenDelete',
        'search-updated' => 'updateSearch',
    ];

    public function mount(
        ?Client $client = null,
        bool $showRadio = false,
        bool $showActions = false,
        bool $showClient = false,
        ?string $selectedTokenIdProperty = 'selectedTokenId',
        string $search = ''
    ) {
        $this->client = $client ?? new Client();
        $this->showRadio = $showRadio;
        $this->showActions = $showActions;
        $this->showClient = $showClient;
        $this->selectedTokenIdProperty = $selectedTokenIdProperty;
        $this->search = $search;
    }

    public function updatedSearch()
    {
        $this->resetPage();
    }

    public function updateSearch($search)
    {
        $this->search = $search;
        $this->resetPage();
    }

    public function handleTokenSelected($tokenId)
    {
        $this->selectedTokenId = $tokenId;
    }

    public function updatedSelectedTokenId($value)
    {
        if ($this->showRadio) {
            // Emitir evento al padre con el token seleccionado
            $this->dispatch('tokenSelected', tokenId: $value);
        }
    }

    public function loadMore()
    {
        $this->nextPage();
    }

    public function openDeleteModal($tokenId)
    {
        $token = LicenseToken::find($tokenId);

        if (!$token) {
            session()->flash('error', 'El token no existe.');
            return;
        }

        $this->dispatch('openModal',
            component: \App\Livewire\Components\ConfirmModal::class,
            arguments: [
                'itemId' => $tokenId,
                'itemName' => $token->token,
                'title' => 'Eliminar token de licencia',
                'message' => '¿Estás seguro de que deseas eliminar este token de licencia? Esta acción no se puede deshacer.',
                'context' => 'token',
                'eventName' => 'tokenDeleted',
                'confirmText' => 'Eliminar',
                'confirmButtonColor' => 'red',
            ]
        );
    }

    public function handleTokenDelete($data)
    {
        $this->authorize('admin.license-tokens.destroy');
        
        $tokenId = $data['itemId'] ?? $data;

        try {
            $token = LicenseToken::findOrFail($tokenId);
            $token->delete();

            session()->flash('success', 'Token eliminado correctamente.');

            // Refrescar la tabla
            $this->resetPage();
        } catch (\Exception $e) {
            session()->flash('error', 'Error al eliminar el token: ' . $e->getMessage());
        }
    }

    public function render()
    {
        if ($this->client->exists) {
            $tokens = $this->client->tokens()
                ->with('products')
                ->withCount('environments')
                ->when($this->search, function ($q) {
                    $q->where('token', 'like', "%{$this->search}%")
                        ->orWhere('name', 'like', "%{$this->search}%");
                })
                ->paginate(20);
        } else {
            $tokens = LicenseToken::with('client')
                ->with('products')
                ->withCount('environments')
                ->when($this->search, function ($q) {
                    $q->where('token', 'like', "%{$this->search}%")
                        ->orWhere('name', 'like', "%{$this->search}%")
                        ->orWhereHas('client', function ($query) {
                            $query->where('name', 'like', "%{$this->search}%");
                        });
                })
                ->orderByDesc('id')
                ->paginate(20);
        }


        return view('livewire.license-tokens.components.licenses-table', [
            'tokens' => $tokens,
        ]);
    }
}
