<?php

namespace App\Livewire\Admin\Cms;

use App\Models\Display;
use App\Models\DisplayVersion;
use Livewire\Component;

class DisplayList extends Component
{
    public $showModal = false;

    public $displayId = null;

    public $displayName = '';

    public $displayLocation = '';

    /** @var array<int> */
    public $selectedVersionIds = [];

    public $displayIsActive = true;

    public $addVersionSelect = null;

    public function openModal(?int $id = null): void
    {
        if ($id) {
            $display = Display::with('versions')->findOrFail($id);
            $this->displayId = $display->id;
            $this->displayName = $display->name;
            $this->displayLocation = $display->location ?? '';
            $this->selectedVersionIds = $display->versions->pluck('id')->toArray();
            $this->displayIsActive = $display->is_active;
        } else {
            $this->resetForm();
        }

        $this->showModal = true;
    }

    public function addVersion(?int $versionId = null): void
    {
        $id = $versionId ?? $this->addVersionSelect;

        if ($id && ! in_array((int) $id, $this->selectedVersionIds)) {
            $this->selectedVersionIds[] = (int) $id;
        }

        $this->addVersionSelect = null;
    }

    public function removeVersion(int $index): void
    {
        array_splice($this->selectedVersionIds, $index, 1);
    }

    public function moveVersion(int $index, string $direction): void
    {
        $newIndex = $direction === 'up' ? $index - 1 : $index + 1;

        if ($newIndex < 0 || $newIndex >= count($this->selectedVersionIds)) {
            return;
        }

        $temp = $this->selectedVersionIds[$index];
        $this->selectedVersionIds[$index] = $this->selectedVersionIds[$newIndex];
        $this->selectedVersionIds[$newIndex] = $temp;
    }

    public function save(): void
    {
        $this->validate([
            'displayName' => 'required|string|max:255',
            'displayLocation' => 'nullable|string|max:255',
            'selectedVersionIds' => 'array',
            'selectedVersionIds.*' => 'exists:display_versions,id',
        ], [
            'displayName.required' => 'Bitte geben Sie einen Namen ein.',
        ]);

        $data = [
            'name' => $this->displayName,
            'location' => $this->displayLocation ?: null,
            'is_active' => $this->displayIsActive,
        ];

        if ($this->displayId) {
            $display = Display::findOrFail($this->displayId);
            $display->update($data);
            session()->flash('success', 'Display erfolgreich aktualisiert!');
        } else {
            $display = Display::create($data);
            session()->flash('success', 'Display erfolgreich erstellt!');
        }

        // Sync versions with sort_order
        $syncData = [];
        foreach ($this->selectedVersionIds as $sortOrder => $versionId) {
            $syncData[$versionId] = ['sort_order' => $sortOrder];
        }
        $display->versions()->sync($syncData);

        $this->closeModal();
    }

    public function deleteDisplay(int $id): void
    {
        $display = Display::findOrFail($id);
        $name = $display->name;
        $display->delete();

        session()->flash('success', 'Display "'.$name.'" wurde gelöscht!');
    }

    public function toggleActive(int $id): void
    {
        $display = Display::findOrFail($id);
        $display->update(['is_active' => ! $display->is_active]);
    }

    public function closeModal(): void
    {
        $this->showModal = false;
        $this->resetForm();
    }

    public function resetForm(): void
    {
        $this->displayId = null;
        $this->displayName = '';
        $this->displayLocation = '';
        $this->selectedVersionIds = [];
        $this->displayIsActive = true;
        $this->addVersionSelect = null;
    }

    public function render()
    {
        $displays = Display::with('versions')
            ->orderBy('name')
            ->get();

        $versions = DisplayVersion::active()
            ->orderBy('name')
            ->get();

        return view('livewire.admin.cms.display-list', [
            'displays' => $displays,
            'versions' => $versions,
        ]);
    }
}
