<?php

namespace App\Livewire\Inventory;

use App\Domain\Identity\Models\Branch;
use App\Domain\Inventory\Models\Warehouse;
use App\Domain\Shared\Exceptions\DomainException;
use App\Models\User;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Layout('layouts.app')]
#[Title('المستودعات')]
class WarehouseForm extends Component
{
    public ?Warehouse $warehouse = null;
    public bool $editing = false;

    public string $name_ar = '';
    public string $name = '';
    public string $code = '';
    public string $type = 'main';
    public ?int $branch_id = null;
    public ?int $manager_id = null;
    public string $address = '';
    public bool $is_active = true;

    public function mount(?Warehouse $warehouse = null): void
    {
        $this->authorize('inventory.create');

        if ($warehouse && $warehouse->exists) {
            $this->authorize('inventory.update');
            $this->warehouse = $warehouse;
            $this->editing = true;

            $this->name_ar = $warehouse->name_ar ?? '';
            $this->name = $warehouse->name ?? '';
            $this->code = $warehouse->code ?? '';
            $this->type = $warehouse->type->value ?? 'main';
            $this->branch_id = $warehouse->branch_id;
            $this->manager_id = $warehouse->manager_id;
            $this->address = $warehouse->address ?? '';
            $this->is_active = $warehouse->is_active;
        }
    }

    public function rules(): array
    {
        $uniqueCode = $this->editing
            ? 'unique:warehouses,code,' . $this->warehouse->id
            : 'unique:warehouses,code';

        return [
            'name_ar' => 'required|string|max:255',
            'name' => 'nullable|string|max:255',
            'code' => ['required', 'string', 'max:20', $uniqueCode],
            'type' => 'required|in:main,sub,transit,returns',
            'branch_id' => 'nullable|exists:branches,id',
            'manager_id' => 'nullable|exists:users,id',
            'address' => 'nullable|string|max:500',
            'is_active' => 'boolean',
        ];
    }

    public function messages(): array
    {
        return [
            'name_ar.required' => 'اسم المستودع بالعربية مطلوب',
            'name_ar.max' => 'اسم المستودع يجب ألا يتجاوز 255 حرف',
            'code.required' => 'كود المستودع مطلوب',
            'code.unique' => 'كود المستودع مستخدم بالفعل',
            'code.max' => 'كود المستودع يجب ألا يتجاوز 20 حرف',
            'type.required' => 'نوع المستودع مطلوب',
            'type.in' => 'نوع المستودع غير صالح',
            'branch_id.exists' => 'الفرع غير موجود',
            'manager_id.exists' => 'المدير غير موجود',
        ];
    }

    public function save(): void
    {
        $this->validate();

        try {
            $data = [
                'name_ar' => $this->name_ar,
                'name' => $this->name ?: null,
                'code' => $this->code,
                'type' => $this->type,
                'branch_id' => $this->branch_id,
                'manager_id' => $this->manager_id,
                'address' => $this->address ?: null,
                'is_active' => $this->is_active,
            ];

            if ($this->editing) {
                $this->warehouse->update($data);
                session()->flash('success', __('تم تحديث المستودع بنجاح'));
            } else {
                $data['created_by'] = auth()->id();
                Warehouse::create($data);
                session()->flash('success', __('تم إنشاء المستودع بنجاح'));
            }

            $this->redirect(route('inventory.warehouses'), navigate: true);
        } catch (DomainException $e) {
            session()->flash('error', $e->getMessage());
        }
    }

    public function render()
    {
        return view('livewire.inventory.warehouse-form', [
            'branches' => Branch::where('is_active', true)->orderBy('name_ar')->get(['id', 'name_ar']),
            'managers' => User::where('is_active', true)->orderBy('name_ar')->get(['id', 'name_ar', 'name']),
            'typeOptions' => [
                'main' => 'رئيسي',
                'sub' => 'فرعي',
                'transit' => 'نقل',
                'returns' => 'مرتجعات',
            ],
        ]);
    }
}
