<?php

namespace App\Livewire\Activities;

use App\Domain\HR\Models\Trainer;
use App\Domain\Shared\Traits\UsesBranchScope;
use App\Domain\Training\Models\Activity;
use App\Domain\Training\Services\ActivityService;
use App\Livewire\Concerns\WithSorting;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Attributes\Url;
use Livewire\Component;

#[Layout('layouts.app')]
#[Title('الأنشطة')]
class ActivityList extends Component
{
    use WithSorting, UsesBranchScope;

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

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

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

    public function updatedSearch(): void
    {
        // Reset not needed without pagination, but keeping for consistency
    }

    public function toggleActive(string $uuid, ActivityService $service): void
    {
        $activity = Activity::where('uuid', $uuid)->firstOrFail();
        $service->toggleActive($activity);
    }

    public function delete(string $uuid, ActivityService $service): void
    {
        try {
            $activity = Activity::where('uuid', $uuid)->firstOrFail();
            $service->delete($activity);
            session()->flash('success', __('تم حذف النشاط بنجاح'));
        } catch (\App\Domain\Shared\Exceptions\DomainException $e) {
            session()->flash('error', $e->getMessage());
        }
    }

    public function render()
    {
        $branchId = $this->getActiveBranchId();
        $query = Activity::query()
            ->withCount('participants')
            ->when($this->search, fn ($q) => $q->where('name_ar', 'ilike', "%{$this->search}%")
                ->orWhere('name', 'ilike', "%{$this->search}%"))
            ->when($this->category, fn ($q) => $q->where('category', $this->category))
            ->orderBy($this->sortBy, $this->sortDir);

        $trainersByActivity = [];
        foreach (Trainer::with('employee.person')->where('status', 'active')
            ->when($branchId, fn ($q) => $q->whereHas('employee', fn ($e) => $e->forBranch($branchId)))
            ->get() as $trainer) {
            if (!empty($trainer->sports)) {
                foreach ($trainer->sports as $actId) {
                    $trainersByActivity[$actId][] = $trainer->employee->person->name_ar ?? '';
                }
            }
        }

        return view('livewire.activities.activity-list', [
            'activities' => $query->get(),
            'trainersByActivity' => $trainersByActivity,
            'categoryLabels' => [
                'sport' => 'رياضة',
                'art' => 'فنون',
                'academic' => 'أكاديمي',
                'fitness' => 'لياقة',
                'other' => 'أخرى',
            ],
        ]);
    }
}
