<?php

use Flux\Flux;
use FluxCms\Core\Models\CmsDownload;
use FluxCms\Core\Services\HeroiconOutlineList;
use function Livewire\Volt\{state, computed, layout, on};

layout('components.layouts.cms');

state([
    'editLocale' => 'de',
    'showForm' => false,
    'editingId' => null,
    'filterCategory' => '',
    'title' => '',
    'description' => '',
    'category' => 'case_study',
    'icon' => 'document-text',
    'sub_category' => '',
    'type_label' => '',
    'alt' => '',
    'file_path' => '',
    'fileMediaId' => null,
    'thumbnail' => '',
    'thumbMediaId' => null,
    'open_text' => '',
    'download_text' => '',
    'highlights' => [],
    'checkpoints' => [],
]);

$downloads = computed(function () {
    $query = CmsDownload::ordered();
    if ($this->filterCategory) {
        $query->byCategory($this->filterCategory);
    }

    return $query->get();
});

$availableIcons = computed(fn () => HeroiconOutlineList::names());

$create = function () {
    $this->reset(['editingId', 'title', 'description', 'icon', 'sub_category', 'type_label', 'alt', 'file_path', 'fileMediaId', 'thumbnail', 'thumbMediaId', 'open_text', 'download_text', 'highlights', 'checkpoints']);
    $this->category = 'case_study';
    $this->icon = 'document-text';
    $this->highlights = [];
    $this->checkpoints = [];
    $this->showForm = true;
};

$edit = function (int $id) {
    $dl = CmsDownload::findOrFail($id);
    $this->editingId = $id;
    $this->showForm = true;
    $l = $this->editLocale;
    $this->title = $dl->getTranslation('title', $l) ?? '';
    $this->description = $dl->getTranslation('description', $l) ?? '';
    $this->category = $dl->category;
    $this->icon = $dl->icon ?? 'document-text';
    $this->sub_category = $dl->sub_category ?? '';
    $this->type_label = $dl->getTranslation('type_label', $l) ?? '';
    $this->alt = $dl->getTranslation('alt', $l) ?? '';
    $this->file_path = $dl->getTranslation('file_path', $l) ?? '';
    $this->thumbnail = $dl->thumbnail ?? '';
    $this->open_text = $dl->getTranslation('open_text', $l) ?? '';
    $this->download_text = $dl->getTranslation('download_text', $l) ?? '';
    $this->highlights = is_array($dl->highlights) ? $dl->highlights : [];
    $this->checkpoints = is_array($dl->checkpoints) ? $dl->checkpoints : [];
    $this->thumbMediaId = $this->thumbnail ? \FluxCms\Core\Models\CmsMedia::where('filename', $this->thumbnail)->first()?->id : null;
    $this->fileMediaId = $this->file_path ? \FluxCms\Core\Models\CmsMedia::where('filename', $this->file_path)->first()?->id : null;
};

$save = function () {
    $existing = $this->editingId ? CmsDownload::find($this->editingId) : null;
    $merge = function (string $field, ?string $value) use ($existing) {
        $t = $existing ? $existing->getTranslations($field) : [];
        $t[$this->editLocale] = $value ?? '';

        return $t;
    };

    $data = [
        'title' => $merge('title', $this->title),
        'description' => $merge('description', $this->description),
        'category' => $this->category,
        'icon' => $this->icon,
        'sub_category' => $this->sub_category,
        'type_label' => $merge('type_label', $this->type_label),
        'alt' => $merge('alt', $this->alt),
        'file_path' => $merge('file_path', $this->file_path),
        'thumbnail' => $this->thumbnail,
        'open_text' => $merge('open_text', $this->open_text),
        'download_text' => $merge('download_text', $this->download_text),
        'highlights' => array_values(array_filter($this->highlights, fn($h) => !empty($h['value']) || !empty($h['label']))),
        'checkpoints' => array_values(array_filter($this->checkpoints, fn($c) => !empty($c['value']))),
    ];

    if ($existing) {
        $existing->update($data);
    } else {
        $data['order'] = CmsDownload::max('order') + 1;
        $data['is_published'] = true;
        CmsDownload::create($data);
    }

    $this->showForm = false;
    $this->editingId = null;

    Flux::toast(variant: 'success', heading: 'Gespeichert', text: 'Download wurde erfolgreich gespeichert.');
};

$delete = function (int $id) {
    CmsDownload::findOrFail($id)->delete();
    Flux::toast(variant: 'success', heading: 'Gelöscht', text: 'Download wurde entfernt.');
};

$togglePublished = function (int $id) {
    $dl = CmsDownload::findOrFail($id);
    $dl->update(['is_published' => !$dl->is_published]);
    Flux::toast(heading: 'Status geändert', text: $dl->is_published ? 'Veröffentlicht' : 'Entwurf');
};

$switchLocale = function (string $locale) {
    $this->editLocale = $locale;
    if ($this->editingId) {
        $dl = CmsDownload::find($this->editingId);
        if ($dl) {
            $this->title = $dl->getTranslation('title', $locale) ?? '';
            $this->description = $dl->getTranslation('description', $locale) ?? '';
            $this->type_label = $dl->getTranslation('type_label', $locale) ?? '';
            $this->alt = $dl->getTranslation('alt', $locale) ?? '';
            $this->file_path = $dl->getTranslation('file_path', $locale) ?? '';
            $this->open_text = $dl->getTranslation('open_text', $locale) ?? '';
            $this->download_text = $dl->getTranslation('download_text', $locale) ?? '';
            $this->fileMediaId = $this->file_path ? \FluxCms\Core\Models\CmsMedia::where('filename', $this->file_path)->first()?->id : null;
        }
    }
};

$cancel = function () {
    $this->showForm = false;
    $this->editingId = null;
};

$addHighlight = function () {
    $this->highlights[] = ['value' => '', 'label' => ''];
};

$removeHighlight = function (int $index) {
    unset($this->highlights[$index]);
    $this->highlights = array_values($this->highlights);
};

$addCheckpoint = function () {
    $this->checkpoints[] = ['value' => ''];
};

$removeCheckpoint = function (int $index) {
    unset($this->checkpoints[$index]);
    $this->checkpoints = array_values($this->checkpoints);
};

$moveUp = function (int $id) {
    $items = CmsDownload::ordered()->get();
    $idx = $items->search(fn($i) => $i->id === $id);
    if ($idx > 0) {
        $prev = $items[$idx - 1];
        $curr = $items[$idx];
        [$prev->order, $curr->order] = [$curr->order, $prev->order];
        $prev->save();
        $curr->save();
    }
};

$moveDown = function (int $id) {
    $items = CmsDownload::ordered()->get();
    $idx = $items->search(fn($i) => $i->id === $id);
    if ($idx !== false && $idx < $items->count() - 1) {
        $next = $items[$idx + 1];
        $curr = $items[$idx];
        [$next->order, $curr->order] = [$curr->order, $next->order];
        $next->save();
        $curr->save();
    }
};

on([
    'media-selected' => function (string $field, ?int $mediaId, ?string $url) {
        if ($field === 'dl_file') {
            $this->fileMediaId = $mediaId;
            $media = $mediaId ? \FluxCms\Core\Models\CmsMedia::find($mediaId) : null;
            $this->file_path = $media ? $media->filename : '';
        } elseif ($field === 'dl_thumb') {
            $this->thumbMediaId = $mediaId;
            $media = $mediaId ? \FluxCms\Core\Models\CmsMedia::find($mediaId) : null;
            $this->thumbnail = $media ? $media->filename : '';
        }
    },
]);

?>

<div>
    <div class="mb-6 flex items-center justify-between">
        <flux:heading size="xl">Downloads</flux:heading>
        <div class="flex items-center gap-2">
            @foreach (config('flux-cms.locales', ['de' => 'DE', 'en' => 'EN']) as $code => $label)
                <flux:button size="xs" :variant="$editLocale === $code ? 'primary' : 'ghost'"
                    wire:click="switchLocale('{{ $code }}')">{{ strtoupper($code) }}</flux:button>
            @endforeach
            <flux:button variant="primary" icon="plus" wire:click="create">Neu</flux:button>
        </div>
    </div>

    {{-- Category Filter --}}
    <div class="mb-4 flex flex-wrap gap-2">
        <flux:button size="xs" :variant="$filterCategory === '' ? 'primary' : 'ghost'"
            wire:click="$set('filterCategory', '')">Alle</flux:button>
        <flux:button size="xs" :variant="$filterCategory === 'case_study' ? 'primary' : 'ghost'"
            wire:click="$set('filterCategory', 'case_study')">Case Studies</flux:button>
        <flux:button size="xs" :variant="$filterCategory === 'capability' ? 'primary' : 'ghost'"
            wire:click="$set('filterCategory', 'capability')">Capabilities</flux:button>
        <flux:button size="xs" :variant="$filterCategory === 'success_story' ? 'primary' : 'ghost'"
            wire:click="$set('filterCategory', 'success_story')">Success Stories</flux:button>
    </div>

    @if ($showForm)
        <flux:card class="mb-6">
            <flux:heading size="lg" class="mb-4">{{ $editingId ? 'Bearbeiten' : 'Neuer Download' }}
            </flux:heading>

            <div class="grid grid-cols-1 gap-4 md:grid-cols-2">
                <flux:input wire:model="title" label="Titel" />
                <flux:select wire:model="category" label="Kategorie">
                    <flux:select.option value="case_study">Case Study</flux:select.option>
                    <flux:select.option value="capability">Capability</flux:select.option>
                    <flux:select.option value="success_story">Success Story</flux:select.option>
                </flux:select>
                <flux:input wire:model="sub_category" label="Unterkategorie" placeholder="z.B. R&D Product Support" />
                <flux:input wire:model="type_label" label="Typ-Label" placeholder="z.B. Case Study" />
                <flux:input wire:model="alt" label="Alt-Text (Bild)" />
                <div>
                    <div class="flex items-end gap-3">
                        <div class="flex-1">
                            <flux:select wire:model="icon" variant="listbox" searchable label="Icon"
                                placeholder="Icon auswählen...">
                                @foreach ($this->availableIcons as $iconName)
                                    <flux:select.option value="{{ $iconName }}">{{ $iconName }}
                                    </flux:select.option>
                                @endforeach
                            </flux:select>
                        </div>
                        @if ($icon)
                            <div
                                class="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg border border-zinc-200 dark:border-zinc-700">
                                <x-dynamic-component :component="'heroicon-o-' . $icon" class="h-6 w-6 text-primary" />
                            </div>
                        @endif
                    </div>
                </div>
            </div>

            {{-- Vorschaubild + PDF --}}
            <div class="mt-4 grid grid-cols-1 gap-4 md:grid-cols-2">
                <div>
                    <label class="mb-1 block text-sm font-medium">Vorschaubild</label>
                    <div class="flex items-start gap-3">
                        @if ($thumbnail)
                            <div
                                class="h-16 w-16 shrink-0 overflow-hidden rounded-lg border border-zinc-200 bg-zinc-50 dark:border-zinc-700 dark:bg-zinc-800">
                                <img src="{{ media_url($thumbnail) }}" class="h-full w-full object-cover" />
                            </div>
                        @endif
                        <div class="flex-1">
                            <livewire:admin.cms.media-picker :value="$thumbMediaId" field="dl_thumb" type="image"
                                profile="thumbnail" label="Bild wählen" :key="'dl-thumb-' . ($editingId ?? 'new')" />
                            <p class="mt-1 text-xs text-zinc-400">{{ $thumbnail ?: 'Kein Bild' }}</p>
                        </div>
                    </div>
                </div>
                <div>
                    <label class="mb-1 block text-sm font-medium">PDF-Datei ({{ strtoupper($editLocale) }})</label>
                    @if ($file_path)
                        <div class="mb-2 overflow-hidden rounded-lg border border-zinc-200 dark:border-zinc-700">
                            <iframe src="{{ media_url($file_path) }}#toolbar=0&navpanes=0" class="h-48 w-full bg-white"
                                loading="lazy"></iframe>
                        </div>
                        <p class="mb-1 text-xs text-zinc-400">{{ $file_path }}</p>
                    @endif
                    <livewire:admin.cms.media-picker :value="$fileMediaId" field="dl_file" type="pdf" profile=""
                        label="PDF wählen" :key="'dl-file-' . ($editingId ?? 'new') . '-' . $editLocale" />
                </div>
            </div>

            {{-- Button-Texte --}}
            <div class="mt-4 grid grid-cols-1 gap-4 md:grid-cols-2">
                <flux:input wire:model="open_text" label="PDF öffnen Text" placeholder="PDF öffnen" />
                <flux:input wire:model="download_text" label="PDF downloaden Text" placeholder="PDF downloaden" />
            </div>

            {{-- Beschreibung --}}
            <div class="mt-4">
                <flux:editor wire:model="description" label="Beschreibung" toolbar="bold italic"
                    class="**:data-[slot=content]:min-h-[80px]!" />
            </div>

            {{-- Highlights (Case Studies / Success Stories) --}}
            @if ($category === 'case_study' || $category === 'success_story')
                <div class="mt-4">
                    <label class="mb-2 block text-sm font-medium">Highlights (Kennzahlen)</label>
                    <div class="space-y-2">
                        @foreach ($highlights as $hIdx => $highlight)
                            <div wire:key="hl-{{ $hIdx }}" class="flex items-center gap-2">
                                <flux:input wire:model="highlights.{{ $hIdx }}.value"
                                    placeholder="Wert (z.B. 100%)" class="w-32!" />
                                <flux:input wire:model="highlights.{{ $hIdx }}.label" placeholder="Label"
                                    class="flex-1!" />
                                <flux:button size="sm" variant="ghost" icon="trash"
                                    wire:click="removeHighlight({{ $hIdx }})" />
                            </div>
                        @endforeach
                    </div>
                    <flux:button size="xs" variant="ghost" icon="plus" wire:click="addHighlight"
                        class="mt-2">
                        Highlight hinzufügen</flux:button>
                </div>
            @endif

            {{-- Checkpoints (Capabilities) --}}
            @if ($category === 'capability')
                <div class="mt-4">
                    <label class="mb-2 block text-sm font-medium">Checkpoints</label>
                    <div class="space-y-2">
                        @foreach ($checkpoints as $cIdx => $checkpoint)
                            <div wire:key="cp-{{ $cIdx }}" class="flex items-center gap-2">
                                <flux:input wire:model="checkpoints.{{ $cIdx }}.value"
                                    placeholder="Checkpoint-Text" class="flex-1!" />
                                <flux:button size="sm" variant="ghost" icon="trash"
                                    wire:click="removeCheckpoint({{ $cIdx }})" />
                            </div>
                        @endforeach
                    </div>
                    <flux:button size="xs" variant="ghost" icon="plus" wire:click="addCheckpoint"
                        class="mt-2">Checkpoint hinzufügen</flux:button>
                </div>
            @endif

            <div class="mt-4 flex gap-2">
                <flux:button variant="primary" wire:click="save">Speichern</flux:button>
                <flux:button variant="ghost" wire:click="cancel">Abbrechen</flux:button>
            </div>
        </flux:card>
    @endif

    <flux:card>
        <div class="divide-y dark:divide-zinc-700">
            @forelse ($this->downloads as $dl)
                <div wire:key="dl-{{ $dl->id }}" class="flex items-center justify-between gap-4 py-3">
                    <div class="flex min-w-0 flex-1 items-center gap-3">
                        @if ($dl->thumbnail)
                            <div class="h-12 w-12 shrink-0 overflow-hidden rounded-lg bg-zinc-100 dark:bg-zinc-700">
                                <img src="{{ media_url($dl->thumbnail) }}" alt=""
                                    class="h-full w-full object-cover" />
                            </div>
                        @elseif ($dl->icon)
                            <div class="flex h-12 w-12 shrink-0 items-center justify-center rounded-lg bg-primary/10">
                                <x-dynamic-component :component="'heroicon-o-' . $dl->icon" class="h-6 w-6 text-primary" />
                            </div>
                        @endif
                        <div class="min-w-0">
                            <div class="flex items-center gap-2">
                                <span class="font-medium">{{ $dl->getTranslation('title', $editLocale) }}</span>
                                <flux:badge size="sm"
                                    :color="$dl->category === 'case_study' ? 'blue' : ($dl->category === 'capability' ? 'green' : 'purple')">
                                    {{ $dl->category === 'case_study' ? 'Case Study' : ($dl->category === 'capability' ? 'Capability' : 'Success Story') }}
                                </flux:badge>
                                @unless ($dl->is_published)
                                    <flux:badge size="sm" color="amber">Entwurf</flux:badge>
                                @endunless
                            </div>
                            <p class="truncate text-sm text-zinc-500">
                                {{ $dl->sub_category }}
                                @if ($dl->getTranslation('file_path', $editLocale))
                                    · {{ $dl->getTranslation('file_path', $editLocale) }}
                                @endif
                            </p>
                        </div>
                    </div>
                    <div class="flex items-center gap-1">
                        <flux:button size="sm" variant="ghost" icon="chevron-up"
                            wire:click="moveUp({{ $dl->id }})" />
                        <flux:button size="sm" variant="ghost" icon="chevron-down"
                            wire:click="moveDown({{ $dl->id }})" />
                        <flux:button size="sm" variant="ghost" icon="pencil"
                            wire:click="edit({{ $dl->id }})" />
                        <flux:button size="sm" variant="ghost" :icon="$dl->is_published ? 'eye' : 'eye-slash'"
                            wire:click="togglePublished({{ $dl->id }})" />
                        <flux:button size="sm" variant="ghost" icon="trash"
                            wire:click="delete({{ $dl->id }})" wire:confirm="Wirklich löschen?" />
                    </div>
                </div>
            @empty
                <flux:text class="py-8 text-center">Keine Downloads vorhanden.</flux:text>
            @endforelse
        </div>
    </flux:card>
</div>
