<?php

namespace App\Livewire;

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

class PhotoUploadComponent extends Component
{
    use WithFileUploads;

    public Park $park;
    public $photo;
    public $title;
    public $description;
    public $alt_text;
    public $credit;
    public $source_url;
    public $is_featured = false;
    public $uploading = false;
    public $uploadError = null;
    public $uploadSuccess = false;

    protected $rules = [
        'photo' => 'required|image|max:10240', // 10MB max
        'title' => 'nullable|string|max:255',
        'description' => 'nullable|string',
        'alt_text' => 'nullable|string|max:255',
        'credit' => 'nullable|string|max:255',
        'source_url' => 'nullable|url|max:255',
        'is_featured' => 'boolean',
    ];

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

    public function updatedPhoto()
    {
        $this->validate([
            'photo' => 'image|max:10240', // 10MB max
        ]);
    }

    public function save()
    {
        $this->uploading = true;
        $this->uploadError = null;
        $this->uploadSuccess = false;

        try {
            $this->validate();

            // Create form data for the API request
            $formData = [
                'photo' => $this->photo,
                'title' => $this->title,
                'description' => $this->description,
                'alt_text' => $this->alt_text,
                'credit' => $this->credit,
                'source_url' => $this->source_url,
                'is_featured' => $this->is_featured,
            ];

            // Make API request to the PhotoController
            $response = app(\App\Http\Controllers\PhotoController::class)->store(
                request: new \Illuminate\Http\Request($formData),
                park: $this->park
            );

            // Reset form
            $this->reset(['photo', 'title', 'description', 'alt_text', 'credit', 'source_url', 'is_featured']);
            $this->uploadSuccess = true;
            
            // Emit event to refresh the photo gallery
            $this->dispatch('photoUploaded');
        } catch (\Exception $e) {
            Log::error('Photo upload error: ' . $e->getMessage());
            $this->uploadError = 'Failed to upload photo: ' . $e->getMessage();
        } finally {
            $this->uploading = false;
        }
    }

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