<?php

namespace App\Livewire\Admin\Cms;

use App\Enums\DisplayVersionType;
use App\Models\DisplayVersion;
use Livewire\Component;

class DisplayVersionList extends Component
{
    public $showCreateModal = false;

    public $newName = '';

    public $newType = '';

    public function openCreateModal(): void
    {
        $this->newName = '';
        $this->newType = '';
        $this->showCreateModal = true;
    }

    public function createVersion(): void
    {
        $this->validate([
            'newName' => 'required|string|max:255',
            'newType' => 'required|string|in:video-display,b2in,offers',
        ], [
            'newName.required' => 'Bitte geben Sie einen Namen ein.',
            'newType.required' => 'Bitte wählen Sie einen Typ aus.',
        ]);

        $version = DisplayVersion::create([
            'name' => $this->newName,
            'type' => $this->newType,
            'settings' => $this->defaultSettingsForType($this->newType),
            'is_active' => true,
        ]);

        $this->showCreateModal = false;
        $this->newName = '';
        $this->newType = '';

        session()->flash('success', 'Version "'.$version->name.'" wurde erstellt!');

        $this->redirect(
            route('admin.cms.display-version-edit', $version),
            navigate: true
        );
    }

    public function deleteVersion(int $id): void
    {
        $version = DisplayVersion::findOrFail($id);
        $name = $version->name;
        $version->delete();

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

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

    /**
     * @return array<string, mixed>
     */
    private function defaultSettingsForType(string $type): array
    {
        return match ($type) {
            'b2in' => [
                'theme' => 'dark',
                'footer_name' => '',
                'footer_url' => '',
                'transition' => ['type' => 'crossfade', 'duration_ms' => 800],
                'default_image_duration' => 10,
                'rotation_weights' => ['immobilien' => 70, 'moebel' => 30],
                'display_active' => true,
            ],
            'offers' => [
                'loop' => true,
                'transition' => ['type' => 'fade', 'duration' => 600],
            ],
            default => [],
        };
    }

    public function render()
    {
        $versions = DisplayVersion::withCount(['items', 'displays'])
            ->orderBy('name')
            ->get();

        return view('livewire.admin.cms.display-version-list', [
            'versions' => $versions,
            'types' => DisplayVersionType::cases(),
        ]);
    }
}
