<?php

namespace App\Livewire;

use Livewire\Component;
use Spatie\MediaLibrary\MediaCollections\Models\Media;

class GalleryPicker extends Component
{
    #[\Livewire\Attributes\Reactive]
    public $entryId;

    public $mediaItems = [];
    public $selectedMediaId = null;
    public $showModal = false;

    #[\Livewire\Attributes\On('open-gallery-picker')]
    public function openPicker($entryId): void
    {
        $this->entryId = $entryId;
        $this->loadMediaItems();
        $this->showModal = true;
    }

    public function loadMediaItems(): void
    {
        $this->mediaItems = Media::where('model_type', 'temp')
            ->where('model_id', 0)
            ->where('disk', 'public')
            ->latest()
            ->limit(30)
            ->get(['id', 'file_name', 'name', 'disk'])
            ->toArray();
    }

    public function selectMedia($mediaId): void
    {
        $this->selectedMediaId = $mediaId;
    }

    public function copyToEntry(): void
    {
        if (!$this->selectedMediaId || !$this->entryId) {
            $this->dispatch('notify-error', ['message' => 'Please select an image']);
            return;
        }

        $sourceMedia = Media::find($this->selectedMediaId);
        if (!$sourceMedia) {
            $this->dispatch('notify-error', ['message' => 'Media not found']);
            return;
        }

        try {
            // Get the entry
            $entry = \App\Models\Entry::find($this->entryId);
            if (!$entry) {
                $this->dispatch('notify-error', ['message' => 'Entry not found']);
                return;
            }

            // Get source file
            $sourceFile = $sourceMedia->getPath();
            if (!file_exists($sourceFile)) {
                $this->dispatch('notify-error', ['message' => 'Source file not found']);
                return;
            }

            // Create temp copy
            $tempCopy = sys_get_temp_dir() . '/' . uniqid() . '_' . $sourceMedia->file_name;
            copy($sourceFile, $tempCopy);

            try {
                // Clear existing featured image
                $entry->clearMediaCollection('featured-image');

                // Add to entry
                $newMedia = $entry->addMedia($tempCopy)
                    ->usingName($sourceMedia->name ?: pathinfo($sourceMedia->file_name, PATHINFO_FILENAME))
                    ->usingFileName($sourceMedia->file_name)
                    ->toMediaCollection('featured-image', 'public');

                // Close modal and notify
                $this->showModal = false;
                $this->selectedMediaId = null;
                $this->dispatch('media-selected', ['mediaId' => $newMedia->id, 'fileName' => $newMedia->file_name]);
                $this->dispatch('notify-success', ['message' => 'Image added to entry']);
            } finally {
                if (file_exists($tempCopy)) {
                    unlink($tempCopy);
                }
            }
        } catch (\Exception $e) {
            $this->dispatch('notify-error', ['message' => 'Error: ' . $e->getMessage()]);
        }
    }

    public function closePicker(): void
    {
        $this->showModal = false;
        $this->selectedMediaId = null;
    }

    public function render()
    {
        return view('livewire.gallery-picker');
    }
}
