<?php

use Flux\Flux;
use function Livewire\Volt\{layout};
layout('components.layouts.cms');

use FluxCms\Core\Models\CmsFaq;
use function Livewire\Volt\{state, computed};

state([
    'editLocale' => 'de',
    'selectedCategory' => null,
    'showForm' => false,
    'editingId' => null,
    'question' => '',
    'answer' => '',
    'help' => '',
    'category' => '',
]);

$categories = computed(fn() => CmsFaq::query()->selectRaw('category, count(*) as count')->groupBy('category')->orderBy('category')->pluck('count', 'category')->toArray());

$faqs = computed(fn() => $this->selectedCategory ? CmsFaq::byCategory($this->selectedCategory)->ordered()->get() : collect());

$selectCategory = function (string $cat) {
    $this->selectedCategory = $cat;
    $this->showForm = false;
    $this->editingId = null;
};

$create = function () {
    $this->resetForm();
    $this->category = $this->selectedCategory ?? '';
    $this->showForm = true;
};

$edit = function (int $id) {
    $faq = CmsFaq::findOrFail($id);
    $this->editingId = $id;
    $this->showForm = true;
    $l = $this->editLocale;
    $this->question = $faq->getTranslation('question', $l) ?? '';
    $this->answer = $faq->getTranslation('answer', $l) ?? '';
    $this->help = $faq->getTranslation('help', $l) ?? '';
    $this->category = $faq->category;
};

$save = function () {
    $existing = $this->editingId ? CmsFaq::find($this->editingId) : null;

    $data = [
        'category' => $this->category,
        'question' => $this->mergeTranslation($existing, 'question', $this->question),
        'answer' => $this->mergeTranslation($existing, 'answer', $this->answer),
        'help' => $this->help ? $this->mergeTranslation($existing, 'help', $this->help) : null,
    ];

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

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

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

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

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

$switchLocale = function (string $locale) {
    $this->editLocale = $locale;
    if ($this->editingId) {
        $faq = CmsFaq::find($this->editingId);
        if ($faq) {
            $this->question = $faq->getTranslation('question', $locale) ?? '';
            $this->answer = $faq->getTranslation('answer', $locale) ?? '';
            $this->help = $faq->getTranslation('help', $locale) ?? '';
        }
    }
};

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

$resetForm = function () {
    $this->editingId = null;
    $this->question = '';
    $this->answer = '';
    $this->help = '';
};

$mergeTranslation = function (?CmsFaq $model, string $field, string $value): array {
    $existing = $model ? $model->getTranslations($field) : [];
    $existing[$this->editLocale] = $value;
    return $existing;
};

?>

<div>
    <div class="mb-6 flex items-center justify-between">
        <flux:heading size="xl">FAQs</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>

    <div class="grid grid-cols-1 gap-6 lg:grid-cols-4">
        <div class="lg:col-span-1">
            <flux:card>
                <flux:heading size="sm" class="mb-3">Kategorien</flux:heading>
                <div class="flex flex-col gap-1">
                    @foreach ($this->categories as $cat => $count)
                        <button wire:click="selectCategory('{{ $cat }}')"
                            class="flex items-center justify-between rounded-lg px-3 py-2 text-sm transition-colors {{ $selectedCategory === $cat ? 'bg-amber-100 text-amber-800 dark:bg-amber-900 dark:text-amber-200' : 'hover:bg-zinc-100 dark:hover:bg-zinc-700' }}">
                            <span>{{ $cat }}</span>
                            <flux:badge size="sm">{{ $count }}</flux:badge>
                        </button>
                    @endforeach
                </div>
            </flux:card>
        </div>

        <div class="lg:col-span-3">
            @if ($showForm)
                <flux:card class="mb-6">
                    <flux:heading size="lg" class="mb-4">{{ $editingId ? 'FAQ bearbeiten' : 'Neue FAQ' }}
                    </flux:heading>
                    <div class="space-y-4">
                        <flux:input wire:model="category" label="Kategorie" />
                        <flux:input wire:model="question" label="Frage" />
                        <flux:editor wire:model="answer" label="Antwort" toolbar="bold italic"
                            class="**:data-[slot=content]:min-h-[80px]!" />
                        <flux:editor wire:model="help" label="Hilfe-Text (optional)" toolbar="bold italic"
                            class="**:data-[slot=content]:min-h-[80px]!" />
                        <div class="flex gap-2">
                            <flux:button variant="primary" wire:click="save">Speichern</flux:button>
                            <flux:button variant="ghost" wire:click="cancel">Abbrechen</flux:button>
                        </div>
                    </div>
                </flux:card>
            @endif

            @if ($selectedCategory)
                <flux:card>
                    <flux:heading size="lg" class="mb-4">{{ $selectedCategory }}</flux:heading>
                    <div class="divide-y dark:divide-zinc-700">
                        @forelse ($this->faqs as $faq)
                            <div wire:key="faq-{{ $faq->id }}"
                                class="flex items-center justify-between gap-4 py-3">
                                <div class="min-w-0 flex-1">
                                    <p class="font-medium">{{ $faq->getTranslation('question', $editLocale) }}</p>
                                    <p class="truncate text-sm text-zinc-600 dark:text-zinc-400">
                                        {{ \Illuminate\Support\Str::limit(strip_tags($faq->getTranslation('answer', $editLocale) ?? ''), 100) }}
                                    </p>
                                </div>
                                <div class="flex items-center gap-1">
                                    <flux:button size="sm" variant="ghost" icon="pencil"
                                        wire:click="edit({{ $faq->id }})" />
                                    <flux:button size="sm" variant="ghost"
                                        :icon="$faq->is_published ? 'eye' : 'eye-slash'"
                                        wire:click="togglePublished({{ $faq->id }})" />
                                    <flux:button size="sm" variant="ghost" icon="trash"
                                        wire:click="delete({{ $faq->id }})" wire:confirm="Wirklich löschen?" />
                                </div>
                            </div>
                        @empty
                            <flux:text class="py-8 text-center">Keine FAQs in dieser Kategorie.</flux:text>
                        @endforelse
                    </div>
                </flux:card>
            @else
                <flux:card>
                    <div class="py-12 text-center">
                        <flux:icon name="question-mark-circle" class="mx-auto mb-4 h-12 w-12 text-zinc-400" />
                        <flux:heading>Kategorie auswählen</flux:heading>
                        <flux:text>Wähle links eine Kategorie, um FAQs zu bearbeiten.</flux:text>
                    </div>
                </flux:card>
            @endif
        </div>
    </div>
</div>
