<?php

namespace App\Livewire\PurchaseOrders;

use App\Models\Product;
use App\Models\PurchaseOrder;
use App\Models\Supplier;
use Livewire\Attributes\Layout;
use Livewire\Component;
use Livewire\WithPagination;

#[Layout('layouts.dashboard')]
class Edit extends Component
{
    use WithPagination;

    public PurchaseOrder $purchaseOrder;

    // General Information
    public string $reference = '';

    public ?int $supplier_id = null;

    public ?string $order_date = null;

    public ?string $expected_delivery_date = null;

    public ?string $notes = '';

    // Add Item Form
    public ?int $product_id = null;

    public int $quantity = 1;

    public string $unit = 'Pièce';

    public float $unit_price = 0;

    // Options
    public array $suppliers = [];

    public array $products = [];

    // UI
    public bool $loading = false;

    public bool $successGeneral = false;

    public bool $successItems = false;

    public function mount(PurchaseOrder $purchaseOrder): void
    {
        $this->purchaseOrder = $purchaseOrder->load(['supplier', 'items.product']);

        // General Information
        $this->reference = $purchaseOrder->reference;
        $this->supplier_id = $purchaseOrder->supplier_id;
        $this->order_date = $purchaseOrder->order_date?->format('Y-m-d');
        $this->expected_delivery_date = $purchaseOrder->expected_delivery_date?->format('Y-m-d');
        $this->notes = $purchaseOrder->notes ?? '';

        // Load options
        $this->loadSuppliers();
        $this->loadProducts();
    }

    public function loadSuppliers(): void
    {
        $this->suppliers = Supplier::orderBy('name')
            ->get()
            ->map(fn ($supplier) => ['id' => $supplier->id, 'name' => $supplier->name])
            ->toArray();
    }

    public function loadProducts(): void
    {
        $this->products = Product::where('status', Product::STATUS_ACTIVE)
            ->with(['purchaseUnit'])
            ->orderBy('name')
            ->get()
            ->map(fn ($product) => ['id' => $product->id, 'name' => $product->name])
            ->toArray();
    }

    public function saveGeneral(): void
    {
        $this->resetErrorBag();
        $this->loading = true;
        try {
            $this->validate([
                'supplier_id' => ['required', 'integer', 'exists:suppliers,id'],
                'order_date' => ['nullable', 'date'],
                'expected_delivery_date' => ['nullable', 'date', 'after_or_equal:order_date'],
                'notes' => ['nullable', 'string', 'max:1000'],
            ]);

            $data = [
                'supplier_id' => $this->supplier_id,
                'order_date' => $this->order_date,
                'expected_delivery_date' => $this->expected_delivery_date,
                'notes' => $this->notes,
            ];

            $this->purchaseOrder->update($data);
            $this->successGeneral = true;
        } catch (\Throwable $e) {
            report($e);
            $this->addError('error_general', "Une erreur est survenue lors de l'enregistrement des informations générales.");
        } finally {
            $this->loading = false;
        }
    }

    public function updatedProductId(): void
    {
        if ($this->product_id) {
            $product = Product::find($this->product_id);
            if ($product && $purchaseUnit = $product->purchaseUnit) {
                $this->unit = $purchaseUnit->name;
                $this->unit_price = $product->purchase_price ?? 0;
            }
        }
    }

    public function addItem(): void
    {
        $this->resetErrorBag();
        $this->loading = true;
        try {
            $this->validate([
                'product_id' => ['required', 'exists:products,id'],
                'quantity' => ['required', 'numeric', 'min:1'],
                'unit_price' => ['required', 'numeric', 'min:0'],
                'unit' => ['required', 'string', 'max:255'],
            ]);

            $this->purchaseOrder->items()->create([
                'product_id' => $this->product_id,
                'quantity' => $this->quantity,
                'unit' => $this->unit,
                'unit_price' => $this->unit_price,
                'total_price' => $this->unit_price * $this->quantity,
            ]);

            // Reset form
            $this->product_id = null;
            $this->quantity = 1;
            $this->unit_price = 0;
            $this->unit = 'Pièce';

            // Reload purchase order with items
            $this->purchaseOrder->load('items.product');
            $this->successItems = true;
        } catch (\Throwable $e) {
            report($e);
            $this->addError('error_items', "Une erreur est survenue lors de l'ajout de l'article.");
        } finally {
            $this->loading = false;
        }
    }

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

        try {
            $item = $this->purchaseOrder->items()->find($itemId);
            if ($item) {
                $item->delete();
                $this->purchaseOrder->load('items.product');
                $this->successItems = true;
            }
        } catch (\Throwable $e) {
            report($e);
            $this->addError('error_items', "Une erreur est survenue lors de la suppression de l'article.");
        }
    }

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