<?php

namespace App\Livewire\Activities;

use App\Domain\Training\Models\Activity;
use App\Domain\Training\Services\ActivityService;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Attributes\Url;
use Livewire\Component;

#[Layout('layouts.app')]
#[Title('الأنشطة')]
class ActivityList extends Component
{
    #[Url]
    public string $search = '';

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

    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()
    {
        $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('sort_order')
            ->orderBy('name_ar');

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