<?php

namespace App\Livewire\Inventory;

use App\Domain\Inventory\Enums\StockCountStatus;
use App\Domain\Inventory\Models\StockCount;
use App\Domain\Inventory\Services\StockCountService;
use App\Domain\Shared\Exceptions\DomainException;
use App\Domain\Shared\Exceptions\InvalidStatusTransitionException;
use App\Livewire\Concerns\AppliesRoleScope;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\WithPagination;

#[Layout('layouts.app')]
#[Title('الجرد المخزني')]
class StockCountList extends Component
{
    use WithPagination, AppliesRoleScope;

    protected string $scopePermission = 'inventory.manage';

    #[Url]
    public string $search = '';

    #[Url]
    public string $statusFilter = '';

    public function mount(): void
    {
        $this->authorize('inventory.manage');
    }

    public function updatedSearch(): void
    {
        $this->resetPage();
    }

    public function updatedStatusFilter(): void
    {
        $this->resetPage();
    }

    public function finalize(int $stockCountId): void
    {
        try {
            $stockCount = StockCount::findOrFail($stockCountId);
            $service = app(StockCountService::class);
            $service->completeCount($stockCount, auth()->user());

            session()->flash('success', __('تم إكمال الجرد بنجاح'));
        } catch (DomainException|InvalidStatusTransitionException $e) {
            session()->flash('error', $e->getMessage());
        } catch (\Exception $e) {
            session()->flash('error', __('حدث خطأ أثناء إكمال الجرد'));
        }
    }

    public function cancel(int $stockCountId): void
    {
        try {
            $stockCount = StockCount::findOrFail($stockCountId);
            $service = app(StockCountService::class);
            $service->cancel($stockCount, auth()->user());

            session()->flash('success', __('تم إلغاء الجرد'));
        } catch (InvalidStatusTransitionException $e) {
            session()->flash('error', $e->getMessage());
        } catch (\Exception $e) {
            session()->flash('error', __('حدث خطأ أثناء إلغاء الجرد'));
        }
    }

    public function render()
    {
        $query = StockCount::query()
            ->with(['warehouse', 'creator'])
            ->withCount('items')
            ->when($this->search, function ($q) {
                $search = $this->search;
                $q->where(function ($q2) use ($search) {
                    $q2->where('count_number', 'ilike', "%{$search}%")
                       ->orWhereHas('warehouse', fn ($w) => $w->where('name_ar', 'ilike', "%{$search}%"));
                });
            })
            ->when($this->statusFilter, fn ($q) => $q->where('status', $this->statusFilter))
            ->orderByDesc('created_at');

        $this->applyRoleScope($query);

        return view('livewire.inventory.stock-count-list', [
            'stockCounts' => $query->paginate(20),
            'statuses' => StockCountStatus::cases(),
        ]);
    }
}
