<?php

namespace App\Livewire\Home\Article;

use App\Enums\CategoryType;
use App\Models\Article;
use App\Models\Category;
use Illuminate\Contracts\View\View;
use Illuminate\Database\Eloquent\Builder;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\WithoutUrlPagination;
use Livewire\WithPagination;

#[Layout('components.layouts.home', [
    'title' => 'Artikel',
])]
class Index extends Component
{
    use WithoutUrlPagination, WithPagination;

    public bool $isDetail = false;

    public ?string $search = null;

    public ?string $sort = null;

    public array $categories = [];

    public array $popularArticles = [];

    public function mount(): void
    {
        $this->categories = Category::query()
            ->where('type', CategoryType::ARTICLE)
            ->orderBy('sort_order')
            ->get()
            ->toArray();

        $this->popularArticles = Article::published()
            ->with(['author', 'categories'])
            ->orderBy('views', 'desc')
            ->take(5)
            ->get()
            ->map(function ($article) {
                $article->thumbnail = $article->getFirstMediaUrl('thumbnail') ? $article->getFirstMediaUrl('thumbnail') : asset('assets/images/dark-logo.png');

                return $article;
            })
            ->toArray();
    }

    #[Url(as: 'category')]
    public ?string $categorySlug = null;

    public function setCategory(?string $slug = null): void
    {
        $this->categorySlug = $slug;

        $this->resetPage();
    }

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

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

    public function render(): View
    {
        $articles = Article::with(['author', 'categories'])
            ->published()
            ->when($this->search, function (Builder $query) {
                $query->where('title', 'like', '%'.$this->search.'%');
            })
            ->when($this->sort, function (Builder $query) {
                match ($this->sort) {
                    'latest' => $query->orderBy('created_at', 'desc'),
                    'Alphabetic' => $query->orderBy('title', 'asc'),
                    'views' => $query->orderBy('views', 'desc'),
                    default => $query->latest(),
                };
            }, fn ($query) => $query->latest())
            ->when($this->categorySlug, function (Builder $query) {
                $query->whereHas('categories', function ($q) {
                    $q->where('slug', $this->categorySlug);
                });
            })
            ->latest()
            ->paginate(9)
            ->through(function (Article $article) {
                $article->thumbnail = $article->getFirstMediaUrl('thumbnail') ? $article->getFirstMediaUrl('thumbnail') : asset('assets/images/dark-logo.png');

                return $article;
            });

        return view('livewire.home.article.index', [
            'pageTitle' => 'Artikel',
            'pageDesc' => 'Baca tips profesional seputar perawatan wewangian, tren lifestyle, dan rekomendasi terbaik.',
            'articles' => $articles,
        ]);
    }
}
