<?php

namespace App\Livewire\Setups;

use App\Models\Products\Product;
use App\Models\Setups\Setup;
use Livewire\Component;
use Livewire\WithFileUploads;
use Symfony\Component\Yaml\Yaml;
use Symfony\Component\Yaml\Exception\ParseException;

class Create extends Component
{
    use WithFileUploads;

    public Product $product;
    public string $version = '';
    public $yamlFile = null;
    public string $yaml = '';
    public ?string $description = null;
    public string $inputMethod = 'editor'; // 'editor' o 'file'
    public ?string $yamlValidationError = null;
    public bool $yamlValid = true;

    public function mount(Product $product)
    {
        $this->product = $product;
    }

    protected function rules()
    {
        $rules = [
            'version' => [
                'required',
                'string',
                'regex:/^\d{10}$/',
                function ($attribute, $value, $fail) {
                    // Validar que no exista un setup con el mismo producto y versión
                    $exists = Setup::where('product_id', $this->product->id)
                        ->where('version', $value)
                        ->exists();
                    
                    if ($exists) {
                        $fail('Ya existe un setup para este producto y versión.');
                    }
                },
            ],
            'description' => 'nullable|string',
        ];

        // Validación condicional según el método de entrada
        if ($this->inputMethod === 'file') {
            $rules['yamlFile'] = [
                'required',
                'file',
                'mimes:yaml,yml',
                'max:10240', // 10MB máximo
            ];
        } else {
            $rules['yaml'] = [
                'required',
                'string',
            ];
        }

        return $rules;
    }

    protected function messages()
    {
        return [
            'productId.required' => 'El producto es obligatorio.',
            'productId.exists' => 'El producto seleccionado no existe.',
            'version.required' => 'La versión es obligatoria.',
            'version.regex' => 'La versión debe tener el formato YYYYMMDDXX (10 dígitos).',
            'yamlFile.required' => 'El archivo YAML es obligatorio.',
            'yamlFile.mimes' => 'El archivo debe ser un archivo YAML (.yaml o .yml).',
            'yamlFile.max' => 'El archivo no puede ser mayor a 10MB.',
            'yaml.required' => 'El contenido YAML es obligatorio.',
        ];
    }

    public function validateYaml()
    {
        $this->yamlValidationError = null;
        $this->yamlValid = true;

        $yamlToValidate = $this->inputMethod === 'file' && $this->yamlFile 
            ? file_get_contents($this->yamlFile->getRealPath())
            : $this->yaml;

        if (empty(trim($yamlToValidate))) {
            $this->yamlValidationError = 'El YAML no puede estar vacío';
            $this->yamlValid = false;
            return;
        }

        try {
            $parsedData = Yaml::parse($yamlToValidate);

            if (!is_array($parsedData)) {
                $this->yamlValidationError = 'El YAML no contiene una estructura válida';
                $this->yamlValid = false;
                return;
            }

            $this->yamlValid = true;
        } catch (ParseException $e) {
            $this->yamlValidationError = 'Error de sintaxis YAML: ' . $e->getMessage();
            $this->yamlValid = false;
        } catch (\Exception $e) {
            $this->yamlValidationError = 'Error al procesar YAML: ' . $e->getMessage();
            $this->yamlValid = false;
        }
    }

    public function updatedYamlFile()
    {
        if ($this->yamlFile) {
            $this->inputMethod = 'file';
            $content = file_get_contents($this->yamlFile->getRealPath());
            if ($content !== false) {
                $this->yaml = $content;
            }
        }
    }

    public function updatedInputMethod()
    {
        // Notificar al frontend del cambio
        $this->dispatch('inputMethodChanged', $this->inputMethod);
    }

    public function save()
    {
        $this->authorize('admin.setups.create');
        
        $validated = $this->validate();

        // Obtener contenido YAML según el método de entrada
        if ($this->inputMethod === 'file' && $this->yamlFile) {
            $yamlContent = file_get_contents($this->yamlFile->getRealPath());

            if ($yamlContent === false) {
                $this->addError('yamlFile', 'No se pudo leer el archivo YAML.');
                return;
            }
        } else {
            $yamlContent = $this->yaml;
        }

        // Validar YAML
        $this->validateYaml();

        if (!$this->yamlValid) {
            if ($this->inputMethod === 'file') {
                $this->addError('yamlFile', $this->yamlValidationError ?? 'YAML inválido');
            } else {
                $this->addError('yaml', $this->yamlValidationError ?? 'YAML inválido');
            }
            return;
        }

        // Guardar en BD
        Setup::create([
            'product_id' => $this->product->id,
            'version' => $validated['version'],
            'yaml' => $yamlContent,
            'status' => 'active',
            'description' => $validated['description'],
            'created_by' => auth()->id(),
        ]);

        session()->flash('success', 'Setup creado correctamente.');

        return $this->redirect(route('products.setups.index', $this->product), navigate: true);
    }

    public function render()
    {
        return view('livewire.setups.create', [
            'product' => $this->product,
        ])->layout('layouts.clean');
    }
}


