<?php

namespace App\Livewire\StockAdjustments;

use App\Models\Product;
use App\Models\StockAdjustment;
use Livewire\Attributes\Layout;
use Livewire\Component;

#[Layout('layouts.dashboard')]
class Edit extends Component
{
    public StockAdjustment $adjustment;

    // General form properties
    public string $type = 'decrease';

    public ?string $reason = null;

    public ?string $notes = null;

    public bool $generalLoading = false;

    public bool $generalSuccess = false;

    // Add item form properties
    public ?int $product_id = null;

    public int $quantity = 1;

    public bool $addItemLoading = false;

    public bool $itemsSuccess = false;

    public bool $disabled = false;

    public array $products = [];

    public function mount(StockAdjustment $stockAdjustment): void
    {
        $this->adjustment = $stockAdjustment->load(['items.product', 'user']);

        // Initialize general form
        $this->type = $this->adjustment->type;
        $this->reason = $this->adjustment->reason;
        $this->notes = $this->adjustment->notes;
        $this->disabled = $this->adjustment->status === StockAdjustment::STATUS_APPLIED;

        // Load active products for the dropdown
        $this->products = Product::where('status', Product::STATUS_ACTIVE)
            ->orderBy('name')
            ->get(['id', 'name'])
            ->map(fn ($p) => (object) ['id' => $p->id, 'name' => $p->name])
            ->toArray();
    }

    public function saveGeneral(): void
    {
        if ($this->disabled) {
            return;
        }

        $this->resetErrorBag();
        $validated = $this->validate([
            'type' => ['required', 'in:increase,decrease'],
            'reason' => ['nullable', 'string', 'max:255'],
            'notes' => ['nullable', 'string', 'max:1000'],
        ]);

        $this->generalLoading = true;

        try {
            $this->adjustment->update($validated);
            $this->generalSuccess = true;
        } catch (\Throwable $e) {
            report($e);
            $this->addError('general_error', "Une erreur est survenue lors de la mise à jour de l'ajustement.");
        } finally {
            $this->generalLoading = false;
        }
    }

    public function addItem(): void
    {
        if ($this->adjustment->status !== StockAdjustment::STATUS_DRAFT) {
            return;
        }

        $this->resetErrorBag();
        $validated = $this->validate([
            'product_id' => ['required', 'exists:products,id'],
            'quantity' => ['required', 'integer', 'min:1'],
        ]);

        $this->addItemLoading = true;

        try {
            $this->adjustment->items()->create([
                'product_id' => $validated['product_id'],
                'quantity' => $validated['quantity'],
            ]);

            $this->adjustment->load('items.product');

            // Reset form
            $this->quantity = 1;
            $this->product_id = null;
            $this->itemsSuccess = true;
            $this->dispatch('clear-input-select-product_id');
        } catch (\Throwable $e) {
            report($e);
            $this->addError('item_error', 'Impossible d\'ajouter l\'article.');
        } finally {
            $this->addItemLoading = false;
        }
    }

    public function deleteItem(int $itemId): void
    {
        if ($this->adjustment->status !== StockAdjustment::STATUS_DRAFT) {
            return;
        }

        $item = $this->adjustment->items()->find($itemId);
        if ($item) {
            $item->delete();
            $this->adjustment->load('items.product');
            $this->itemsSuccess = true;
        }
    }

    public function render(): \Illuminate\Contracts\View\View
    {
        return view('livewire.stock-adjustments.edit');
    }
}
