<?php

namespace App\Livewire\Programs;

use App\Domain\Shared\Traits\UsesBranchScope;
use App\Domain\Training\Enums\ProgramStatus;
use App\Domain\Training\Models\Activity;
use App\Domain\Training\Models\TrainingProgram;
use App\Domain\Training\Services\TrainingProgramService;
use App\Domain\Shared\Exceptions\DomainException;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\WithPagination;

#[Layout('layouts.app')]
#[Title('البرامج التدريبية')]
class ProgramList extends Component
{
    use WithPagination, UsesBranchScope;

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

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

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

    #[Url]
    public string $sortBy = 'created_at';

    #[Url]
    public string $sortDir = 'desc';

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

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

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

    public function sortColumn(string $column): void
    {
        if ($this->sortBy === $column) {
            $this->sortDir = $this->sortDir === 'asc' ? 'desc' : 'asc';
        } else {
            $this->sortBy = $column;
            $this->sortDir = 'asc';
        }
    }

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

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

        $query = TrainingProgram::query()
            ->with(['activity', 'branch'])
            ->withCount('groups')
            ->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
            ->when($this->search, fn ($q) => $q->where(function ($sub) {
                $sub->where('name_ar', 'ilike', "%{$this->search}%")
                    ->orWhere('name', 'ilike', "%{$this->search}%");
            }))
            ->when($this->status, fn ($q) => $q->where('status', $this->status))
            ->when($this->activityFilter, fn ($q) => $q->where('activity_id', $this->activityFilter))
            ->orderBy($this->sortBy, $this->sortDir);

        return view('livewire.programs.program-list', [
            'programs' => $query->paginate(15),
            'activities' => Activity::where('is_active', true)->orderBy('name_ar')->get(['id', 'name_ar']),
            'statusOptions' => [
                'draft' => 'مسودة',
                'active' => 'نشط',
                'full' => 'ممتلئ',
                'closed' => 'مغلق',
                'archived' => 'مؤرشف',
            ],
        ]);
    }
}
