<?php

namespace App\Livewire\Plan;

use App\Livewire\Data\PlanData;
use App\Models\Plan;
use Exception;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Jantinnerezo\LivewireAlert\LivewireAlert;
use Livewire\Attributes\Locked;
use Livewire\Attributes\On;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\WithPagination;

final class PlanComponent extends Component
{
    use LivewireAlert;
    use WithPagination;

    #[Url]
    public string $search = '';

    #[Locked]
    public string $plan = '';

    #[Locked]
    public string $modalTitle = '';

    #[Locked]
    public PlanData $detailData;

    public function render()
    {
        $planes = Plan::search($this->search)
            // ->paginate(15);
            ->get();
        if (session()->has('message')) $this->alert(session('type'), session('message'));

        return view('livewire.plan.plan-component', ['planes' => $planes]);
    }

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

    public function detail(string $uuid)
    {
        try {
            $plan = Plan::where('uuid', $uuid)->firstOrFail();

            $this->fill([
                'modalTitle' => "Información $plan->nombre",
                'detailData' => PlanData::create($plan->toArray())
            ]);

            $this->dispatch('show-detail');
        } catch (ModelNotFoundException $e) {
            $this->alert('error', 'Plan no encontrado.', [
                'timer' => 5000,
            ]);
        } catch (Exception $e) {
            throw_if(env('APP_DEBUG'), $e);
            $this->alert('error', 'Error al mostrar el detalle del plan.', [
                'timer' => 5000,
            ]);
        }
    }

    public function confirmDelete(string $uuid)
    {
        $this->plan = $uuid;

        $this->alert('warning', '¿Estas seguro?', [
            'position' => 'center',
            'text' => '¡Si elimina este plan no podra restaurarlo!',
            'showConfirmButton' => true,
            'confirmButtonText' => '¡Eliminar!',
            'showCancelButton' => true,
            'cancelButtonText' => 'Cancelar',
            'toast' => false,
            'onConfirmed' => 'confirmedDelete',
            'onDeny' => 'deniedDelete',
            'timer' => null,
            'reverseButtons' => true,
            'confirmButtonColor' => '#3085d6',
            'cancelButtonColor' => '#d33',
        ]);
    }

    public function getListeners()
    {
        return [
            'confirmedDelete',
            'deniedDelete',
        ];
    }

    #[On('confirmedDelete')]
    public function confirmedDelete()
    {
        try {
            $plan = Plan::where('uuid', $this->plan)->first();

            if ($plan) {
                if ($plan->remotas()->count() > 0) {
                    $this->alert('error', 'No se puede eliminar el plan, tiene remotas asignadas.');
                } else {

                    $plan->delete();
                    $this->alert(message: 'Plan eliminado con exito.');
                    $this->search = '';
                }
            }
        } catch (Exception $e) {
            throw_if(env('APP_DEBUG'), $e);
            $this->alert('error', 'Error al eliminar el plan.');
        }
    }

    #[On('deniedDelete')]
    public function deniedDelete()
    {
        $this->plan = '';
    }
}
