<?php

namespace App\Livewire\Admin\Cms;

use App\Models\DisplayFooterContent;
use App\Models\DisplayVideo;
use Illuminate\Support\Facades\File;
use Livewire\Component;

class CabinetDisplay extends Component
{
    // Video-Verwaltung
    public $videoId = null;

    public $videoFilename = '';

    public $videoTitle = '';

    public $videoPosition = 25;

    public $videoIsActive = true;

    public $showVideoModal = false;

    public $availableVideos = [];

    // Footer-Content-Verwaltung
    public $footerId = null;

    public $footerHeadline = '';

    public $footerSubline = '';

    public $footerUrl = '';

    public $footerIsActive = true;

    public $showFooterModal = false;

    public function mount()
    {
        $this->loadAvailableVideos();
    }

    /**
     * Lädt alle verfügbaren Video-Dateien aus dem assets-Ordner
     */
    public function loadAvailableVideos()
    {
        $assetsPath = public_path('_cabinet/assets');

        if (File::exists($assetsPath)) {
            $files = File::files($assetsPath);
            $this->availableVideos = collect($files)
                ->map(fn ($file) => $file->getFilename())
                ->filter(fn ($filename) => in_array(pathinfo($filename, PATHINFO_EXTENSION), ['mp4', 'webm', 'mov']))
                ->values()
                ->toArray();
        }
    }

    // ========================================
    // VIDEO-VERWALTUNG
    // ========================================

    public function openVideoModal($id = null)
    {
        if ($id) {
            $video = DisplayVideo::findOrFail($id);
            $this->videoId = $video->id;
            $this->videoFilename = $video->filename;
            $this->videoTitle = $video->title ?? '';
            $this->videoPosition = $video->position;
            $this->videoIsActive = $video->is_active;
        } else {
            $this->resetVideoForm();
        }
        $this->showVideoModal = true;
    }

    public function saveVideo()
    {
        $this->validate([
            'videoFilename' => 'required|string',
            'videoPosition' => 'required|integer|min:0|max:100',
        ], [
            'videoFilename.required' => 'Bitte wählen Sie ein Video aus.',
            'videoPosition.required' => 'Die Position ist erforderlich.',
            'videoPosition.min' => 'Die Position muss zwischen 0 und 100 liegen.',
            'videoPosition.max' => 'Die Position muss zwischen 0 und 100 liegen.',
        ]);

        $data = [
            'filename' => $this->videoFilename,
            'title' => $this->videoTitle,
            'position' => $this->videoPosition,
            'is_active' => $this->videoIsActive,
        ];

        if ($this->videoId) {
            $video = DisplayVideo::findOrFail($this->videoId);
            $video->update($data);
            session()->flash('success', 'Video erfolgreich aktualisiert!');
        } else {
            $maxSortOrder = DisplayVideo::max('sort_order') ?? 0;
            $data['sort_order'] = $maxSortOrder + 1;
            DisplayVideo::create($data);
            session()->flash('success', 'Video erfolgreich hinzugefügt!');
        }

        $this->closeVideoModal();
    }

    public function deleteVideo($id)
    {
        DisplayVideo::findOrFail($id)->delete();
        session()->flash('success', 'Video erfolgreich gelöscht!');
    }

    public function toggleVideoStatus($id)
    {
        $video = DisplayVideo::findOrFail($id);
        $video->update(['is_active' => ! $video->is_active]);
    }

    public function moveVideo($id, $direction)
    {
        $video = DisplayVideo::findOrFail($id);
        $currentOrder = $video->sort_order;

        if ($direction === 'up' && $currentOrder > 0) {
            $swapVideo = DisplayVideo::where('sort_order', $currentOrder - 1)->first();
            if ($swapVideo) {
                $video->update(['sort_order' => $currentOrder - 1]);
                $swapVideo->update(['sort_order' => $currentOrder]);
            }
        } elseif ($direction === 'down') {
            $swapVideo = DisplayVideo::where('sort_order', $currentOrder + 1)->first();
            if ($swapVideo) {
                $video->update(['sort_order' => $currentOrder + 1]);
                $swapVideo->update(['sort_order' => $currentOrder]);
            }
        }
    }

    public function resetVideoForm()
    {
        $this->videoId = null;
        $this->videoFilename = '';
        $this->videoTitle = '';
        $this->videoPosition = 25;
        $this->videoIsActive = true;
    }

    public function closeVideoModal()
    {
        $this->showVideoModal = false;
        $this->resetVideoForm();
    }

    // ========================================
    // FOOTER-CONTENT-VERWALTUNG
    // ========================================

    public function openFooterModal($id = null)
    {
        if ($id) {
            $footer = DisplayFooterContent::findOrFail($id);
            $this->footerId = $footer->id;
            $this->footerHeadline = $footer->headline;
            $this->footerSubline = $footer->subline;
            $this->footerUrl = $footer->url;
            $this->footerIsActive = $footer->is_active;
        } else {
            $this->resetFooterForm();
        }
        $this->showFooterModal = true;
    }

    public function saveFooter()
    {
        $this->validate([
            'footerHeadline' => 'required|string|max:255',
            'footerSubline' => 'required|string|max:255',
            'footerUrl' => 'nullable|url',
        ], [
            'footerHeadline.required' => 'Die Überschrift ist erforderlich.',
            'footerSubline.required' => 'Die Unterzeile ist erforderlich.',
            'footerUrl.url' => 'Bitte geben Sie eine gültige URL ein.',
        ]);

        $data = [
            'headline' => $this->footerHeadline,
            'subline' => $this->footerSubline,
            'url' => $this->footerUrl ?: null,
            'is_active' => $this->footerIsActive,
        ];

        if ($this->footerId) {
            $footer = DisplayFooterContent::findOrFail($this->footerId);
            $footer->update($data);

            // Short-Code generieren falls URL vorhanden aber noch kein Short-Code
            if ($footer->url && ! $footer->short_code) {
                $footer->short_code = DisplayFooterContent::generateUniqueShortCode();
                $footer->save();
            }

            session()->flash('success', 'Footer-Inhalt erfolgreich aktualisiert!');
        } else {
            $maxSortOrder = DisplayFooterContent::max('sort_order') ?? 0;
            $data['sort_order'] = $maxSortOrder + 1;

            $footer = DisplayFooterContent::create($data);

            // Short-Code nur generieren wenn URL vorhanden
            if ($footer->url) {
                $footer->short_code = DisplayFooterContent::generateUniqueShortCode();
                $footer->save();
                session()->flash('success', 'Footer-Inhalt erfolgreich hinzugefügt! Short-Link: '.$footer->short_url);
            } else {
                session()->flash('success', 'Footer-Inhalt erfolgreich hinzugefügt! (Ohne QR-Code)');
            }
        }

        $this->closeFooterModal();
    }

    public function regenerateShortCode($id)
    {
        $footer = DisplayFooterContent::findOrFail($id);
        $footer->short_code = DisplayFooterContent::generateUniqueShortCode();
        $footer->save();
        session()->flash('success', 'Short-Code wurde neu generiert!');
    }

    public function resetClicks($id)
    {
        $footer = DisplayFooterContent::findOrFail($id);
        $footer->clicks = 0;
        $footer->save();
        session()->flash('success', 'Klick-Zähler wurde zurückgesetzt!');
    }

    public function deleteFooter($id)
    {
        DisplayFooterContent::findOrFail($id)->delete();
        session()->flash('success', 'Footer-Inhalt erfolgreich gelöscht!');
    }

    public function toggleFooterStatus($id)
    {
        $footer = DisplayFooterContent::findOrFail($id);
        $footer->update(['is_active' => ! $footer->is_active]);
    }

    public function moveFooter($id, $direction)
    {
        $footer = DisplayFooterContent::findOrFail($id);
        $currentOrder = $footer->sort_order;

        if ($direction === 'up' && $currentOrder > 0) {
            $swapFooter = DisplayFooterContent::where('sort_order', $currentOrder - 1)->first();
            if ($swapFooter) {
                $footer->update(['sort_order' => $currentOrder - 1]);
                $swapFooter->update(['sort_order' => $currentOrder]);
            }
        } elseif ($direction === 'down') {
            $swapFooter = DisplayFooterContent::where('sort_order', $currentOrder + 1)->first();
            if ($swapFooter) {
                $footer->update(['sort_order' => $currentOrder + 1]);
                $swapFooter->update(['sort_order' => $currentOrder]);
            }
        }
    }

    public function resetFooterForm()
    {
        $this->footerId = null;
        $this->footerHeadline = '';
        $this->footerSubline = '';
        $this->footerUrl = '';
        $this->footerIsActive = true;
    }

    public function closeFooterModal()
    {
        $this->showFooterModal = false;
        $this->resetFooterForm();
    }

    public function render()
    {
        $videos = DisplayVideo::orderBy('sort_order')->get();
        $footerContents = DisplayFooterContent::orderBy('sort_order')->get();

        return view('livewire.admin.cms.cabinet-display', [
            'videos' => $videos,
            'footerContents' => $footerContents,
        ]);
    }
}
