<?php

namespace App\Livewire\Projects;

use App\Jobs\ProjectMosiacGeneratorJob;
use App\Models\Project;
use Livewire\Attributes\Lazy;
use Livewire\Component;
use Livewire\WithPagination;

#[Lazy]
class MosaicManager extends Component
{
    use WithPagination;

    public $project;

    public $formData = [
        'week' => '',
        'year' => '',
    ];
    public $showCreateModal = false;

    public $search = "";

    public function mount(Project $project)
    {
        $this->path = $project->download_path;
    }
    public function saveMosaic()
    {
        $this->validate([
            'formData.year' => 'required',
            'formData.week' => 'required',
        ]);

        $mosaic = $this->project->mosaics()->updateOrCreate([
            'name' => sprintf('Week %s, %s', str_pad($this->formData['week'], 2, '0', STR_PAD_LEFT), $this->formData['year']),
            'year' => $this->formData['year'],
            'week' => $this->formData['week'],
        ], [
            'path' => $this->project->getMosaicPath(),
        ]);
        logger(sprintf('in SaveMosaic: %s, week: %d, year: %d', $mosaic->name, $mosaic->week, $mosaic->year));
        ProjectMosiacGeneratorJob::dispatch($mosaic);

        $this->showCreateModal = false;
    }

    public function openCreateMosiacsModal()
    {
        $this->showCreateModal = true;
    }

    public function getDateRangeProperty()
    {
        if (empty($this->formData['week']) || strlen($this->formData['year']) !== 4) {
            return '<span class="text-red-500">Invalid week or year</span>';
        }
        $begin = now()
            ->setISODate($this->formData['year'], $this->formData['week'])
            ->startOfWeek();
        $end = now()
            ->setISODate($this->formData['year'], $this->formData['week'])
            ->endOfWeek();
        return $begin->format('Y-m-d').' - '.$end->format('Y-m-d');
    }

    private function applySearch($query)
    {
        if ($this->search) {
            $query->where('name', 'like', '%' . $this->search . '%');
            $query->orWhere('year', 'like', '%' . $this->search . '%');
            $query->orWhere('week', 'like', '%' . $this->search . '%');
        }
        return $query;
    }

    public function update($property)
    {
        if ($property === 'search') {
            $this->resetPage('mosaicPage');
        }
    }
    public function placeholder()
    {
        return view('livewire.projects.mosaic-manager-placeholder');
    }

    public function render()
    {
        $query = $this->project->mosaics()
            ->orderBy('year', 'desc')
            ->orderBy('week', 'desc');
        $query = $this->applySearch($query);
        $mosaics = $query->paginate(10, pageName: 'mosaicPage');

        return view('livewire.projects.mosaic-manager', [
            'mosaics' => $mosaics
        ]);
    }
}
