<?php

namespace App\Livewire;

use App\Models\Episode;
use Illuminate\Support\Facades\Auth;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\WithPagination;

class LiveSearch extends Component
{
    use WithPagination;

    #[Url(history: true)]
    public $search = '';

    #[Url(history: true)]
    public $order = 'recently-uploaded';

    #[Url(history: true)]
    public $tags = [];

    public $tagsCopy = [];

    #[Url(history: true)]
    public $studios = [];

    public $studiosCopy = [];

    #[Url(history: true)]
    public $blacklist = [];

    public $blacklistCopy = [];

    #[Url(history: true)]
    public $hideWatched = [];

    #[Url(history: true)]
    public $view = 'thumbnail';

    public $pagination = 25;

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

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

    public function updatedView(): void
    {
        $this->pagination = $this->view == 'thumbnail' ? 25 : 24;
        $this->resetPage();
    }

    public function revertFilters(): void
    {
        $this->tags = $this->tagsCopy;
        $this->studios = $this->studiosCopy;
        $this->blacklist = $this->blacklistCopy;
    }

    public function applyFilters(): void
    {
        $this->tagsCopy = $this->tags;
        $this->studiosCopy = $this->studios;
        $this->blacklistCopy = $this->blacklist;
        $this->resetPage();
    }

    public function mount()
    {
        // User blacklist
        if (Auth::check() && empty($this->blacklist) && ! empty(auth()->user()->tag_blacklist)) {
            $this->blacklist = auth()->user()->tag_blacklist;
        }

        if (Auth::check()) {
            $this->view = auth()->user()->search_design ? 'thumbnail' : 'poster';
            $this->pagination = $this->view == 'thumbnail' ? 25 : 24;
        }
    }

    public function render()
    {
        $orderby = 'created_at';
        $orderdirection = 'desc';

        switch ($this->order) {
            case 'az':
                $orderby = 'title';
                $orderdirection = 'asc';
                break;
            case 'za':
                $orderby = 'title';
                $orderdirection = 'desc';
                break;
            case 'recently-released':
                $orderby = 'release_date';
                $orderdirection = 'desc';
                break;
            case 'oldest-uploads':
                $orderby = 'created_at';
                $orderdirection = 'asc';
                break;
            case 'oldest-releases':
                $orderby = 'release_date';
                $orderdirection = 'asc';
                break;
            case 'view-count':
                $orderby = 'view_count';
                $orderdirection = 'desc';
                break;
            default:
                $orderby = 'created_at';
                $orderdirection = 'desc';
        }

        $user_id = Auth::check() ? auth()->user()->id : 0;
        $episodes = Episode::with('gallery')->when($this->search != '', fn ($query) => $query->where(function ($query) {
            $query->where('title', 'like', '%'.$this->search.'%')->orWhere('title_search', 'like', '%'.$this->search.'%')->orWhere('title_jpn', 'like', '%'.$this->search.'%');
        }))
            ->when($this->tags !== [], fn ($query) => $query->withAllTags($this->tags))
            ->when($this->blacklist !== [], fn ($query) => $query->withoutTags($this->blacklist))
            ->when($this->studios !== [], fn ($query) => $query->whereHas('studio', function ($query) {
                $query->whereIn('slug', $this->studios);
            }))
            ->when($this->hideWatched !== [] && Auth::check(), fn ($query) => $query->whereDoesntHave('watched', function ($query) use ($user_id) {
                $query->where('user_id', $user_id);
            }))
            ->when(Auth::guest(), fn ($query) => $query->withoutTags(['loli', 'shota']))
            ->orderBy($orderby, $orderdirection)
            ->paginate($this->pagination);

        $searchIsJpn = false;
        if (! empty($this->search)) {
            if (strlen($this->search) != strlen(utf8_decode($this->search))) {
                $searchIsJpn = true;
            }
        }

        // Dispatch Event to trigger JS reload for thumbnails
        $this->dispatch('contentChanged');

        return view('livewire.live-search', [
            'episodes' => $episodes,
            'tagcount' => is_array($this->tags) ? count($this->tags) : 0,
            'studiocount' => is_array($this->studios) ? count($this->studios) : 0,
            'blacklistcount' => is_array($this->blacklist) ? count($this->blacklist) : 0,
            'query' => $this->search,
            'selectedtags' => $this->tags,
            'selectedstudios' => $this->studios,
            'selectedblacklist' => $this->blacklist,
            'searchIsJpn' => $searchIsJpn,
            'view' => $this->view,
        ]);
    }
}
