<?php

namespace App\Livewire\Skills;

use App\Domain\Skill\Enums\Framework;
use App\Domain\Skill\Enums\SkillStatus;
use App\Domain\Skill\Enums\SkillType;
use App\Domain\Skill\Models\Skill;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\WithPagination;

class SkillListPage extends Component
{
    use WithPagination;

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

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

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

    #[Url(as: 'framework')]
    public string $frameworkFilter = '';

    public string $sortField = 'created_at';

    public string $sortDirection = 'desc';

    public function sortBy(string $field): void
    {
        if ($this->sortField === $field) {
            $this->sortDirection = $this->sortDirection === 'asc' ? 'desc' : 'asc';
        } else {
            $this->sortField = $field;
            $this->sortDirection = 'asc';
        }
    }

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

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

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

    public function render()
    {
        $query = Skill::query();

        if ($this->search) {
            $query->where(function ($q) {
                $q->where('name', 'ilike', "%{$this->search}%")
                    ->orWhere('description', 'ilike', "%{$this->search}%");
            });
        }

        if ($this->typeFilter) {
            $query->where('type', $this->typeFilter);
        }

        if ($this->statusFilter) {
            $query->where('status', $this->statusFilter);
        }

        if ($this->frameworkFilter && Framework::tryFrom($this->frameworkFilter)) {
            $query->where('framework', $this->frameworkFilter);
        }

        $query->orderBy($this->sortField, $this->sortDirection);

        return view('livewire.skills.skill-list-page', [
            'skills' => $query->paginate(20),
            'types' => SkillType::cases(),
            'statuses' => SkillStatus::cases(),
            'frameworks' => Framework::cases(),
            'canCreate' => true,
        ])->layout('layouts.app', ['header' => 'Skills']);
    }
}
