<?php

namespace App\Livewire;

use App\Models\Ride;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Storage;
use Livewire\Component;
use Livewire\WithFileUploads;
use Livewire\Attributes\Rule;

class RideGalleryComponent extends Component
{
    use WithFileUploads;

    /** @var Ride */
    public Ride $ride;

    /** @var \Illuminate\Http\UploadedFile */
    #[Rule('image|max:10240')] // 10MB Max
    public $photo;

    /** @var string|null */
    public ?string $caption = null;

    /** @var bool */
    public bool $showUploadForm = false;

    public function mount(Ride $ride): void
    {
        $this->ride = $ride;
    }

    public function toggleUploadForm(): void
    {
        $this->showUploadForm = !$this->showUploadForm;
        $this->reset(['photo', 'caption']);
    }

    public function save(): void
    {
        $this->validate([
            'photo' => 'required|image|max:10240',
            'caption' => 'nullable|string|max:255',
        ]);

        $path = $this->photo->store('ride-photos', 'public');
        
        $this->ride->photos()->create([
            'path' => $path,
            'caption' => $this->caption,
            'uploaded_by' => Auth::id(),
        ]);

        $this->reset(['photo', 'caption']);
        $this->showUploadForm = false;
        
        session()->flash('message', 'Photo uploaded successfully.');
    }

    public function deletePhoto(int $photoId): void
    {
        $photo = $this->ride->photos()->findOrFail($photoId);
        
        if ($photo->uploaded_by === Auth::id() || Gate::allows('delete-any-photo')) {
            Storage::disk('public')->delete($photo->path);
            $photo->delete();
            session()->flash('message', 'Photo deleted successfully.');
        } else {
            session()->flash('error', 'You do not have permission to delete this photo.');
        }
    }

    public function setFeaturedPhoto(int $photoId): void
    {
        if (Gate::allows('edit', $this->ride)) {
            $this->ride->featured_photo_id = $photoId;
            $this->ride->save();
            session()->flash('message', 'Featured photo updated.');
        } else {
            session()->flash('error', 'You do not have permission to set the featured photo.');
        }
    }

    public function render()
    {
        return view('livewire.ride-gallery', [
            'photos' => $this->ride->photos()->latest()->paginate(12),
        ]);
    }
}