<?php

namespace App\Livewire\Inventory;

use App\Domain\Inventory\Models\Product;
use App\Domain\Inventory\Models\ProductCategory;
use App\Domain\Shared\Exceptions\DomainException;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Layout('layouts.app')]
#[Title('إنشاء منتج جديد')]
class CreateProductWizard extends Component
{
    public int $currentStep = 1;
    public int $totalSteps = 4;
    public bool $completed = false;

    // Step 1: Basic Info
    public string $nameAr = '';
    public string $name = '';
    public string $sku = '';
    public string $barcode = '';
    public ?int $categoryId = null;
    public string $type = 'physical';
    public string $descriptionAr = '';

    // Step 2: Pricing
    public string $sellingPrice = '';
    public string $costPrice = '';
    public string $taxRate = '0';

    // Step 3: Inventory Settings
    public bool $trackInventory = true;
    public ?int $minStockLevel = null;
    public ?int $maxStockLevel = null;
    public bool $isActive = true;

    // Data
    public array $categories = [];

    public function mount(): void
    {
        $this->authorize('products.create');
        $this->categories = ProductCategory::active()
            ->orderBy('name_ar')
            ->get(['id', 'name_ar', 'name'])
            ->toArray();
    }

    public function getStepLabels(): array
    {
        return [
            1 => 'المعلومات الأساسية',
            2 => 'التسعير',
            3 => 'إعدادات المخزون',
            4 => 'مراجعة',
        ];
    }

    public function rulesForStep(): array
    {
        return match ($this->currentStep) {
            1 => [
                'nameAr' => 'required|string|max:255',
                'name' => 'nullable|string|max:255',
                'sku' => 'nullable|string|max:50',
                'barcode' => 'nullable|string|max:50',
                'categoryId' => 'nullable|exists:product_categories,id',
                'type' => 'required|in:physical,digital,service',
                'descriptionAr' => 'nullable|string|max:1000',
            ],
            2 => [
                'sellingPrice' => 'required|numeric|min:0.01',
                'costPrice' => 'nullable|numeric|min:0',
                'taxRate' => 'nullable|numeric|min:0|max:100',
            ],
            3 => [
                'trackInventory' => 'boolean',
                'minStockLevel' => 'nullable|integer|min:0',
                'maxStockLevel' => 'nullable|integer|min:0',
                'isActive' => 'boolean',
            ],
            default => [],
        };
    }

    public function messages(): array
    {
        return [
            'nameAr.required' => 'اسم المنتج بالعربية مطلوب',
            'type.required' => 'نوع المنتج مطلوب',
            'type.in' => 'نوع المنتج غير صالح',
            'categoryId.exists' => 'التصنيف المختار غير موجود',
            'sellingPrice.required' => 'سعر البيع مطلوب',
            'sellingPrice.min' => 'سعر البيع يجب أن يكون أكبر من صفر',
            'costPrice.numeric' => 'سعر التكلفة يجب أن يكون رقمًا',
            'taxRate.numeric' => 'نسبة الضريبة يجب أن تكون رقمًا',
            'taxRate.max' => 'نسبة الضريبة لا يمكن أن تتجاوز 100%',
            'minStockLevel.integer' => 'الحد الأدنى يجب أن يكون رقمًا صحيحًا',
            'maxStockLevel.integer' => 'الحد الأقصى يجب أن يكون رقمًا صحيحًا',
        ];
    }

    public function nextStep(): void
    {
        $this->validate($this->rulesForStep(), $this->messages());
        $this->currentStep = min($this->currentStep + 1, $this->totalSteps);
    }

    public function previousStep(): void
    {
        $this->currentStep = max($this->currentStep - 1, 1);
    }

    public function goToStep(int $step): void
    {
        if ($step < $this->currentStep) {
            $this->currentStep = $step;
        }
    }

    public function confirm(): void
    {
        try {
            Product::create([
                'name_ar' => $this->nameAr,
                'name' => $this->name ?: null,
                'sku' => $this->sku ?: null,
                'barcode' => $this->barcode ?: null,
                'category_id' => $this->categoryId,
                'type' => $this->type,
                'description_ar' => $this->descriptionAr ?: null,
                'selling_price' => (int) round((float) $this->sellingPrice * 100),
                'cost_price' => $this->costPrice ? (int) round((float) $this->costPrice * 100) : null,
                'tax_rate' => $this->taxRate ? (int) $this->taxRate : 0,
                'track_inventory' => $this->trackInventory,
                'min_stock_level' => $this->minStockLevel,
                'max_stock_level' => $this->maxStockLevel,
                'is_active' => $this->isActive,
                'created_by' => auth()->id(),
            ]);

            $this->completed = true;
            session()->flash('success', 'تم إنشاء المنتج بنجاح');
        } catch (DomainException $e) {
            session()->flash('error', $e->getMessage());
        }
    }

    public function render()
    {
        return view('livewire.inventory.create-product-wizard');
    }
}
