<?php

namespace App\Livewire\Tecnico;

use App\Livewire\Data\PersonaData;
use App\Livewire\Data\TecnicoData;
use App\Models\Persona;
use App\Models\Tecnico;
use Exception;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Jantinnerezo\LivewireAlert\LivewireAlert;
use Livewire\Attributes\Locked;
use Livewire\Attributes\On;
use Livewire\Component;
use Livewire\WithPagination;

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

    public string $search = '';

    public string $persona = '';

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

    #[Locked]
    public $detailData;
    // public TecnicoData $detailData;

    public function render()
    {
        $search = $this->search;

        $tecnicos = Tecnico::whereHas('persona', function ($query) use ($search) {
            $query->where('nombres', 'like', "%$search%")
                ->orWhere('cedula', 'like', "%$search%")
                ->orWhere('telefono', 'like', "%$search%")
                ->orWhere('correo', 'like', "%$search%");
        })->paginate(15);

        if (session()->has('message')) $this->alert(session('type'), session('message'));
        return view('livewire.tecnico.tecnico-component', ['tecnicos' => $tecnicos]);
    }

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

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

            $this->fill([
                'modalTitle' => "Información $persona->nombres",
                'detailData' => $persona
                // 'detailData' => new TecnicoData(PersonaData::create($persona->toArray())),
            ]);

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

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

        $this->alert('warning', '¿Estas seguro?', [
            'position' => 'center',
            'text' => '¡Si elimina a este técnico 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 {
            $persona = Persona::with('tecnico')->where('uuid', $this->persona)->first();

            if ($persona->tecnico) {
                $persona->tecnico->delete();
                $this->alert(message: 'Técnico eliminado con exito.');
                $this->search = '';
            }
        } catch (Exception $e) {
            throw_if(env('APP_DEBUG'), $e);
            $this->alert('error', 'Error al eliminar al técnico.');
        }
    }

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