<?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 Edit extends Component
{
    use WithFileUploads;

    public Product $product;
    public FeatureVersion $featureVersion;
    public Feature $feature;
    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, Feature $feature)
    {
        $this->product = $product;
        $this->featureVersion = $featureVersion;
        $this->feature = $feature->load(['featureVersion.product', 'creator']);

        // 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.');
        }

        // Verificar que la feature pertenezca a la versión
        if ($this->feature->feature_version_id !== $this->featureVersion->id) {
            abort(404, 'La feature no pertenece a esta versión.');
        }

        $this->title = $feature->title;
        $this->description = $feature->description;
        $this->content_html = $feature->content_html ?? '';
        $this->status = $feature->status;
        $this->sort_order = $feature->sort_order;
    }

    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.edit');
        
        $validated = $this->validate();

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

        // Actualizar feature con HTML saneado
        $this->feature->update([
            'title' => $validated['title'],
            'description' => $validated['description'],
            'content_html' => $sanitizedHtml,
            'status' => $validated['status'],
            'sort_order' => $validated['sort_order'],
        ]);

        $imageService = app(FeatureImageService::class);

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

        // Guardar nuevas imágenes estructurales si existen

        if ($this->thumbnail_image) {
            // Eliminar imagen anterior si existe
            if ($this->feature->thumbnail_image) {
                $imageService->deleteImage($this->feature->thumbnail_image);
            }
            
            $thumbnailPath = $imageService->storeThumbnail($this->feature, $this->thumbnail_image);
            $this->feature->update(['thumbnail_image' => $thumbnailPath]);
        }

        if ($this->header_image) {
            // Eliminar imagen anterior si existe
            if ($this->feature->header_image) {
                $imageService->deleteImage($this->feature->header_image);
            }
            
            $headerPath = $imageService->storeHeader($this->feature, $this->header_image);
            $this->feature->update(['header_image' => $headerPath]);
        }

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

        // Redirigir a la vista de la versión
        return $this->redirect(route('products.features.version.show', [$this->product, $this->featureVersion]), navigate: true);
    }

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

