<?php

namespace App\Livewire;

use App\Models\Playlist;
use App\Models\PlaylistEpisode;
use App\Services\PlaylistService;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\Auth;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\WithPagination;

class PlaylistOverview extends Component
{
    use WithPagination;

    protected PlaylistService $playlistService;

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

    public int $pagination = 25;

    public Playlist $playlist;

    public Collection $playlistEpisodes;

    public function boot(PlaylistService $playlistService)
    {
        $this->playlistService = $playlistService;
    }

    public function mount($playlist_id)
    {
        $this->playlist = Playlist::with(['episodes.episode'])->findOrFail($playlist_id);

        // Set position if null
        $this->playlist->episodes->each(function ($item, $index) {
            if ($item->position === null) {
                $item->position = $index + 1;
                $item->save();
            }
        });

        $this->refreshEpisodes();
    }

    public function refreshEpisodes()
    {
        $this->playlistEpisodes = $this->playlist->episodes()->orderBy('position')->with('episode')->get();
    }

    public function moveUp($episodeId)
    {
        if (! Auth::check()) {
            return;
        }

        if (Auth::user()->id !== $this->playlist->user->id) {
            return;
        }

        $episode = PlaylistEpisode::find($episodeId);
        $above = PlaylistEpisode::where('playlist_id', $episode->playlist_id)
            ->where('position', '<', $episode->position)
            ->orderBy('position', 'desc')
            ->first();

        if ($above) {
            $this->playlistService->swapPositions($episode, $above);
        }

        $this->refreshEpisodes();
    }

    public function moveDown($episodeId)
    {
        if (! Auth::check()) {
            return;
        }

        if (Auth::user()->id !== $this->playlist->user->id) {
            return;
        }

        $episode = PlaylistEpisode::find($episodeId);
        $below = PlaylistEpisode::where('playlist_id', $episode->playlist_id)
            ->where('position', '>', $episode->position)
            ->orderBy('position')
            ->first();

        if ($below) {
            $this->playlistService->swapPositions($episode, $below);
        }

        $this->refreshEpisodes();
    }

    public function remove($episodeId)
    {
        if (! Auth::check()) {
            return;
        }

        if (Auth::user()->id !== $this->playlist->user->id) {
            return;
        }

        PlaylistEpisode::find($episodeId)?->delete();
        $this->playlistService->reorderPositions($this->playlist);
        $this->refreshEpisodes();
    }

    public function render()
    {
        return view('livewire.playlist-overview', [
            'query' => $this->search,
        ]);
    }
}
