<?php

namespace App\Livewire\Setups;

use App\Models\Products\Product;
use App\Models\Setups\Setup;
use Livewire\Component;

class Show extends Component
{
    public Product $product;
    public Setup $setup;
    public ?int $historyIdToView = null;

    public function mount(Product $product, Setup $setup)
    {
        $this->product = $product;
        $this->setup = $setup->load(['product', 'creator', 'updater', 'history.changer']);
    }

    public function toggleStatus()
    {
        $newStatus = $this->setup->status === 'active' ? 'deprecated' : 'active';
        $this->setup->update([
            'status' => $newStatus,
            'updated_by' => auth()->id(),
            'change_log' => "Estado cambiado a {$newStatus}",
        ]);

        // Crear entrada en historial
        $this->setup->createHistoryEntry("Estado cambiado a {$newStatus}");

        $statusLabel = $newStatus === 'active' ? 'activo' : 'deprecado';
        session()->flash('success', "Setup marcado como {$statusLabel} correctamente.");
    }

    public function duplicate()
    {
        try {
            $newSetup = $this->setup->duplicate();
            session()->flash('success', "Setup duplicado. Nueva versión: {$newSetup->version}");

            return $this->redirect(route('products.setups.edit', [$this->product, $newSetup]), navigate: true);
        } catch (\Exception $e) {
            session()->flash('error', $e->getMessage());
        }
    }

    public function viewHistoryYaml($historyId)
    {
        $this->historyIdToView = $historyId;
    }

    public function closeHistoryModal()
    {
        $this->historyIdToView = null;
        $this->dispatch('history-modal-closed');
    }

    public function render()
    {
        $historyYaml = null;
        if ($this->historyIdToView) {
            $historyEntry = $this->setup->history->firstWhere('id', $this->historyIdToView);
            $historyYaml = $historyEntry?->yaml;
        }

        return view('livewire.setups.show', [
            'product' => $this->product,
            'historyYaml' => $historyYaml,
        ])->layout('layouts.app');
    }
}

