<?php

namespace App\Livewire\Features;

use App\Models\Features\Feature;
use App\Models\Features\FeatureVersion;
use App\Models\Products\Product;
use App\Services\Features\FeatureImageService;
use App\Services\Features\HtmlSanitizer;
use Livewire\Component;
use Livewire\WithFileUploads;

class Create extends Component
{
    use WithFileUploads;

    public Product $product;
    public FeatureVersion $featureVersion;
    public string $title = '';
    public ?string $description = null;
    public string $content_html = '';
    public $thumbnail_image = null;
    public $header_image = null;
    public string $status = 'draft';
    public ?int $sort_order = null;

    public function mount(Product $product, FeatureVersion $featureVersion)
    {
        $this->product = $product;
        $this->featureVersion = $featureVersion;
        
        // Verificar que la versión pertenezca al producto
        if ($this->featureVersion->product_id !== $this->product->id) {
            abort(404, 'La versión de Features no pertenece a este producto.');
        }
    }

    protected function rules()
    {
        return [
            'title' => 'required|string|max:255',
            'description' => 'nullable|string|max:1000',
            'content_html' => 'nullable|string',
            'thumbnail_image' => ['nullable', 'file', 'mimes:jpeg,jpg,png,webp,svg', 'max:5120'],
            'header_image' => ['nullable', 'file', 'mimes:jpeg,jpg,png,webp,svg', 'max:5120'],
            'status' => 'required|in:draft,published,archived',
            'sort_order' => 'nullable|integer|min:0',
        ];
    }

    protected function messages()
    {
        return [
            'title.required' => 'El título es obligatorio.',
            'title.max' => 'El título no puede tener más de 255 caracteres.',
            'description.max' => 'La descripción no puede tener más de 1000 caracteres.',
            'thumbnail_image.file' => 'La miniatura debe ser un archivo válido.',
            'thumbnail_image.mimes' => 'La miniatura debe ser jpg, png, webp o svg.',
            'thumbnail_image.max' => 'La miniatura no puede ser mayor a 5MB.',
            'header_image.file' => 'La imagen de cabecera debe ser un archivo válido.',
            'header_image.mimes' => 'La imagen de cabecera debe ser jpg, png, webp o svg.',
            'header_image.max' => 'La imagen de cabecera no puede ser mayor a 5MB.',
            'status.required' => 'El estado es obligatorio.',
            'status.in' => 'El estado debe ser draft, published o archived.',
            'sort_order.integer' => 'El orden debe ser un número entero.',
            'sort_order.min' => 'El orden debe ser mayor o igual a 0.',
        ];
    }

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

        // Sanitizar HTML
        $htmlSanitizer = app(HtmlSanitizer::class);
        $sanitizedHtml = $htmlSanitizer->sanitize($validated['content_html'] ?? '');

        // Crear feature
        $feature = Feature::create([
            'feature_version_id' => $this->featureVersion->id,
            'title' => $validated['title'],
            'description' => $validated['description'],
            'content_html' => $sanitizedHtml,
            'status' => $validated['status'],
            'sort_order' => $validated['sort_order'],
            'created_by' => auth()->id(),
        ]);

        $imageService = app(FeatureImageService::class);

        // Migrar imágenes temporales usadas en el HTML a la ruta definitiva de la feature
        $updatedHtml = $imageService->migrateTempImagesForFeature($feature, $sanitizedHtml);
        if ($updatedHtml !== $sanitizedHtml) {
            $feature->update(['content_html' => $updatedHtml]);
        }

        // Guardar imágenes estructurales si existen

        if ($this->thumbnail_image) {
            $thumbnailPath = $imageService->storeThumbnail($feature, $this->thumbnail_image);
            $feature->update(['thumbnail_image' => $thumbnailPath]);
        }

        if ($this->header_image) {
            $headerPath = $imageService->storeHeader($feature, $this->header_image);
            $feature->update(['header_image' => $headerPath]);
        }

        session()->flash('success', 'Feature creada correctamente.');

        return $this->redirect(route('products.features.version.show', [$this->product, $this->featureVersion]), navigate: true);
    }

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

