<?php

namespace App\Livewire\Facilities;

use App\Domain\Facility\Enums\FacilityStatus;
use App\Domain\Facility\Enums\FacilityType;
use App\Domain\Facility\Models\Facility;
use App\Domain\Facility\Services\FacilityService;
use App\Domain\Identity\Models\Branch;
use App\Domain\Shared\Exceptions\DomainException;
use App\Domain\Shared\Traits\UsesBranchScope;
use App\Livewire\Concerns\AppliesRoleScope;
use App\Livewire\Concerns\WithSorting;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\WithPagination;

#[Layout('layouts.app')]
#[Title('المنشآت')]
class FacilityList extends Component
{
    use WithPagination, WithSorting, UsesBranchScope, AppliesRoleScope;

    protected string $scopePermission = 'facilities.list';

    public function mount(): void
    {
        if (! request()->has('sortBy')) {
            $this->sortBy = 'name_ar';
            $this->sortDir = 'asc';
        }
    }

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

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

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

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

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

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

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

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

    public function delete(string $uuid, FacilityService $service): void
    {
        try {
            $facility = Facility::where('uuid', $uuid)->firstOrFail();
            $service->delete($facility);
            session()->flash('success', __('تم حذف المنشأة بنجاح'));
        } catch (DomainException $e) {
            session()->flash('error', $e->getMessage());
        }
    }

    public function render()
    {
        $branchId = $this->branch_id ?: $this->getActiveBranchId();

        $query = Facility::query()
            ->with('branch')
            ->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
            ->when($this->search, function ($q) {
                $search = $this->search;
                $q->where(function ($q2) use ($search) {
                    $q2->where('name_ar', 'ilike', "%{$search}%")
                       ->orWhere('name', 'ilike', "%{$search}%")
                       ->orWhere('code', 'ilike', "%{$search}%");
                });
            })
            ->when($this->status, fn ($q) => $q->where('status', $this->status))
            ->when($this->type, fn ($q) => $q->where('type', $this->type))
            ->orderBy($this->sortBy, $this->sortDir);

        $this->applyRoleScope($query);

        return view('livewire.facilities.facility-list', [
            'facilities' => $query->paginate(20),
            'branches' => Branch::orderBy('name_ar')->get(['id', 'name_ar']),
            'statusOptions' => collect(FacilityStatus::cases())->mapWithKeys(fn ($s) => [$s->value => $s->label()]),
            'typeOptions' => collect(FacilityType::cases())->mapWithKeys(fn ($t) => [$t->value => $t->label()]),
        ]);
    }
}
