<?php

namespace Daylight\Core\Modules\MediaLibrary\Livewire;

use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Collection as SupportCollection;
use Illuminate\View\View;
use Livewire\Attributes\On;
use Livewire\Component;

class MediaSelector extends Component
{
    public string $name;

    public array $selectedMedia = [];

    public bool $singleFile = false;

    public string $displayType = 'gallery';

    public string $instanceId;

    public function mount(string $name, Collection|SupportCollection|array $initialMedia = [], bool $singleFile = false, string $displayType = 'gallery'): void
    {
        $this->name = $name;
        $this->instanceId = 'media-selector-' . uniqid();

        // Transform Media models to the expected format with URLs
        if ($initialMedia instanceof Collection || $initialMedia instanceof SupportCollection) {
            $this->selectedMedia = $initialMedia->map(function ($media) {
                // If it's already an array or object, handle it appropriately
                if (is_array($media)) {
                    return $media;
                }

                if (is_object($media) && ! method_exists($media, 'getUrl')) {
                    // It's a stdClass or similar object
                    return [
                        'id' => (int) ($media->id ?? 0),
                        'name' => (string) ($media->name ?? ''),
                        'handle' => (string) ($media->handle ?? ''),
                        'type' => (string) ($media->type ?? ''),
                        'size' => (int) ($media->size ?? 0),
                        'url' => (string) ($media->url ?? ''),
                    ];
                }

                // It's a Media model
                return [
                    'id' => (int) $media->id,
                    'name' => (string) $media->name,
                    'handle' => (string) $media->handle,
                    'type' => (string) $media->type,
                    'size' => (int) $media->size,
                    'url' => (string) $media->getUrl('thumbnail'),
                ];
            })->toArray();
        } else {
            $this->selectedMedia = $initialMedia;
        }

        $this->singleFile = $singleFile;
        $this->displayType = $displayType;
    }

    public function openMediaLibrary(): void
    {
        $this->dispatch('open-media-library', instanceId: $this->instanceId);

        // Force update MediaLibrary selection when opening - always sync current state
        $this->dispatch('sync-media-library-selection', [
            'instanceId' => $this->instanceId,
            'selectedItems' => $this->selectedMedia,
        ]);
    }

    #[On('media-files-selected')]
    public function filesSelected(array $data): void
    {
        $files = $data['files'] ?? [];
        $instanceId = $data['instanceId'] ?? null;

        //        // Only process if this event is for this instance
        //        // If instanceId is provided, it must match this instance
        //        if ($instanceId !== null && $instanceId !== $this->instanceId) {
        //            return;
        //        }
        //
        //        // If no instanceId is provided in event but we have one, ignore it (safety check)
        //        if ($instanceId === null && isset($this->instanceId)) {
        //            return;
        //        }

        // Only process if this event is for this instance
        // Always require instanceId to match - if it doesn't match or is missing, ignore
        if ($instanceId === null || $instanceId !== $this->instanceId) {
            return;
        }

        $this->selectedMedia = $files;
        $this->dispatch('close-media-library');
    }

    #[On('file-deleted')]
    public function onFileDeleted(int $id): void
    {
        $this->selectedMedia = collect($this->selectedMedia)
            ->reject(fn ($item) => (int) ($item['id'] ?? 0) === $id)
            ->values()
            ->toArray();
    }

    public function removeItem(int $index): void
    {
        array_splice($this->selectedMedia, $index, 1);
        $this->selectedMedia = array_values($this->selectedMedia);

        $this->dispatch('sync-media-library-selection', [
            'instanceId' => $this->instanceId,
            'selectedItems' => $this->selectedMedia,
        ]);
    }

    public function reorderItems(int $fromIndex, int $toIndex): void
    {
        $item = $this->selectedMedia[$fromIndex];
        array_splice($this->selectedMedia, $fromIndex, 1);
        array_splice($this->selectedMedia, $toIndex, 0, [$item]);
        $this->selectedMedia = array_values($this->selectedMedia);
    }

    public function updateOrder(array $order): void
    {
        $reordered = [];
        foreach ($order as $id) {
            foreach ($this->selectedMedia as $item) {
                if ($item['id'] === $id) {
                    $reordered[] = $item;
                    break;
                }
            }
        }
        $this->selectedMedia = $reordered;
    }

    public function render(): View
    {
        return view('daylight::livewire.media.media-selector');
    }
}
