<?php

namespace App\Livewire\Environments;

use App\Models\Clients\Client;
use App\Models\Environments\Environment;
use Livewire\Component;
use Livewire\WithPagination;

class CreateWizard extends Component
{
    use WithPagination;

    public int $currentStep = 1;
    public ?int $selectedClientId = null;
    public string $searchQuery = '';
    public array $formData = [];
    public ?int $createdEnvironmentId = null;

    protected $paginationTheme = 'tailwind';

    public function mount()
    {
        $this->currentStep = 1;
        $this->formData = [
            'name' => '',
            'domain' => '',
            'description' => null,
            'version' => '',
            'env' => 'local',
            'type_id' => null,
        ];
    }

    public function selectClient($clientId)
    {
        $this->selectedClientId = $clientId;
        $this->formData['client_id'] = $clientId;
    }

    public function updatedSelectedClientId()
    {
        // Cuando se selecciona un cliente, actualizar formData
        if ($this->selectedClientId) {
            $this->formData['client_id'] = $this->selectedClientId;
        }
    }

    public function nextStep()
    {
        if ($this->currentStep === 1) {
            // Validar que se haya seleccionado un cliente
            if (!$this->selectedClientId) {
                session()->flash('error', 'Por favor, selecciona un cliente.');
                return;
            }
            $this->currentStep = 2;
        } elseif ($this->currentStep === 2) {
            // Validar formulario antes de avanzar
            $this->validateStep2();
            // No avanzar aquí, el formulario se envía con saveEnvironment
        }
    }

    public function previousStep()
    {
        if ($this->currentStep > 1) {
            $this->currentStep--;
        }
    }

    protected function validateStep2()
    {
        $this->validate([
            'formData.name' => 'required|string|max:255',
            'formData.domain' => 'required|string|max:255|unique:environments,domain',
            'formData.description' => 'nullable|string',
            'formData.version' => 'required|string|max:50',
            'formData.env' => 'required|string|in:local,develop,pre,pro',
            'formData.type_id' => 'nullable|exists:types,id',
        ], [], [
            'formData.name' => 'nombre',
            'formData.domain' => 'dominio',
            'formData.version' => 'versión',
            'formData.env' => 'desarrollo',
            'formData.type_id' => 'tipo de entorno',
        ]);
    }

    public function updatedFormData()
    {
        // Resetear errores cuando se actualiza el formulario
    }

    public function saveEnvironment()
    {
        $this->validateStep2();

        $data = $this->formData;
        $data['client_id'] = $this->selectedClientId;
        $data['active'] = true;

        $environment = Environment::create($data);
        $this->createdEnvironmentId = $environment->id;
        $this->currentStep = 3;
    }

    public function updatedSearchQuery()
    {
        // Resetear paginación cuando cambia la búsqueda
        $this->resetPage();
    }

    public function getClientsProperty()
    {
        $query = Client::query();

        if (!empty($this->searchQuery)) {
            $query->where(function($q) {
                $q->where('name', 'like', '%' . $this->searchQuery . '%')
                  ->orWhere('shortname', 'like', '%' . $this->searchQuery . '%');
            });
        }

        $clients = $query->orderBy('name')->paginate(10);

        // Agregar environments_count a cada cliente
        $clients->getCollection()->transform(function ($client) {
            $client->environments_count = $client->environments()->count();
            return $client;
        });

        return $clients;
    }

    public function render()
    {
        return view('livewire.environments.create-wizard')->layout('layouts.clean');
    }
}

