<?php

namespace App\Livewire;

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

class FeaturedPhotoSelectorComponent extends Component
{
    public Park $park;
    public $photos = [];
    public $featuredPhotoId = null;
    public $isLoading = true;
    public $error = null;
    public $success = false;

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

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

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

        try {
            $this->photos = $this->park->photos()->ordered()->get();
            $featuredPhoto = $this->park->featuredPhoto();
            $this->featuredPhotoId = $featuredPhoto ? $featuredPhoto->id : null;
            $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 setFeatured($photoId)
    {
        $this->isLoading = true;
        $this->error = null;
        $this->success = false;

        try {
            $photo = Photo::findOrFail($photoId);
            
            if ($photo->photoable_id !== $this->park->id || $photo->photoable_type !== Park::class) {
                throw new \Exception('Photo does not belong to this park');
            }
            
            $success = $this->park->setFeaturedPhoto($photo);
            
            if ($success) {
                $this->featuredPhotoId = $photoId;
                $this->success = true;
                $this->dispatch('notify', [
                    'type' => 'success',
                    'message' => 'Featured photo updated successfully'
                ]);
                
                // Emit event to refresh other components
                $this->dispatch('featuredPhotoChanged');
            } else {
                throw new \Exception('Failed to set featured photo');
            }
        } catch (\Exception $e) {
            Log::error('Error setting featured photo: ' . $e->getMessage());
            $this->error = 'Failed to set featured photo: ' . $e->getMessage();
            $this->dispatch('notify', [
                'type' => 'error',
                'message' => 'Failed to set featured photo'
            ]);
        } finally {
            $this->isLoading = false;
        }
    }

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