<?php

namespace App\Livewire;

use App\Models\Park;
use Livewire\Component;
use Illuminate\Support\Facades\Log;

class PhotoManagerComponent extends Component
{
    public Park $park;
    public $photos = [];
    public $isLoading = true;
    public $error = null;
    public $reordering = false;
    public $photoOrder = [];

    protected $listeners = ['photoUploaded' => 'loadPhotos'];

    public function mount(Park $park)
    {
        $this->park = $park;
        $this->loadPhotos();
    }

    public function loadPhotos()
    {
        $this->isLoading = true;
        $this->error = null;

        try {
            $this->photos = $this->park->photos()->ordered()->get()->toArray();
            $this->photoOrder = collect($this->photos)->pluck('id')->toArray();
            $this->isLoading = false;
        } catch (\Exception $e) {
            Log::error('Error loading photos: ' . $e->getMessage());
            $this->error = 'Failed to load photos: ' . $e->getMessage();
            $this->isLoading = false;
        }
    }

    public function startReordering()
    {
        $this->reordering = true;
    }

    public function cancelReordering()
    {
        $this->reordering = false;
        $this->loadPhotos(); // Reset to original order
    }

    public function saveOrder()
    {
        try {
            // Make API request to the PhotoController
            app(\App\Http\Controllers\PhotoController::class)->reorder(
                request: new \Illuminate\Http\Request(['photo_ids' => $this->photoOrder]),
                park: $this->park
            );
            
            $this->reordering = false;
            $this->loadPhotos();
            
            $this->dispatch('notify', [
                'type' => 'success',
                'message' => 'Photo order updated successfully'
            ]);
        } catch (\Exception $e) {
            Log::error('Error reordering photos: ' . $e->getMessage());
            $this->dispatch('notify', [
                'type' => 'error',
                'message' => 'Failed to update photo order: ' . $e->getMessage()
            ]);
        }
    }

    public function moveUp($index)
    {
        if ($index > 0) {
            $temp = $this->photoOrder[$index - 1];
            $this->photoOrder[$index - 1] = $this->photoOrder[$index];
            $this->photoOrder[$index] = $temp;
        }
    }

    public function moveDown($index)
    {
        if ($index < count($this->photoOrder) - 1) {
            $temp = $this->photoOrder[$index + 1];
            $this->photoOrder[$index + 1] = $this->photoOrder[$index];
            $this->photoOrder[$index] = $temp;
        }
    }

    public function render()
    {
        return view('livewire.photo-manager-component');
    }
}