<?php

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

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

state([
    'editLocale' => 'de',
    'showForm' => false,
    'editingId' => null,
    'name' => '',
    'order' => 0,
]);

$industries = computed(fn () => CmsIndustry::ordered()->get());

$create = function () {
    $this->editingId = null;
    $this->name = '';
    $this->order = CmsIndustry::max('order') + 1;
    $this->showForm = true;
};

$edit = function (int $id) {
    $item = CmsIndustry::findOrFail($id);
    $this->editingId = $id;
    $this->name = $item->getTranslation('name', $this->editLocale) ?? '';
    $this->order = $item->order;
    $this->showForm = true;
};

$save = function () {
    $existing = $this->editingId ? CmsIndustry::find($this->editingId) : null;
    $translations = $existing ? $existing->getTranslations('name') : [];
    $translations[$this->editLocale] = $this->name;

    if ($existing) {
        $existing->update(['name' => $translations, 'order' => (int) $this->order]);
    } else {
        CmsIndustry::create([
            'name' => $translations,
            'order' => (int) $this->order,
            'is_published' => true,
        ]);
    }

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

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

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

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

$switchLocale = function (string $locale) {
    $this->editLocale = $locale;
    if ($this->editingId) {
        $item = CmsIndustry::find($this->editingId);
        $this->name = $item?->getTranslation('name', $locale) ?? '';
    }
};

$moveUp = function (int $id) {
    $items = CmsIndustry::ordered()->get();
    $index = $items->search(fn($i) => $i->id === $id);

    if ($index === false || $index === 0) {
        return;
    }

    $prev = $items[$index - 1];
    $current = $items[$index];

    $tmpOrder = $prev->order;
    $prev->update(['order' => $current->order]);
    $current->update(['order' => $tmpOrder]);

    Flux::toast(heading: 'Verschoben', text: 'Position geändert.');
};

$moveDown = function (int $id) {
    $items = CmsIndustry::ordered()->get();
    $index = $items->search(fn($i) => $i->id === $id);

    if ($index === false || $index >= $items->count() - 1) {
        return;
    }

    $next = $items[$index + 1];
    $current = $items[$index];

    $tmpOrder = $next->order;
    $next->update(['order' => $current->order]);
    $current->update(['order' => $tmpOrder]);

    Flux::toast(heading: 'Verschoben', text: 'Position geändert.');
};

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

?>

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

    @if ($showForm)
        <flux:card class="mb-6">
            <flux:heading size="lg" class="mb-4">{{ $editingId ? 'Bearbeiten' : 'Neue Industry' }}</flux:heading>
            <div class="space-y-4">
                <div class="grid grid-cols-1 gap-4 md:grid-cols-4">
                    <div class="md:col-span-3">
                        <flux:input wire:model="name" label="Name" />
                    </div>
                    <flux:input wire:model="order" label="Reihenfolge" type="number" min="0" />
                </div>
                <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

    <flux:card>
        <div class="divide-y dark:divide-zinc-700">
            @forelse ($this->industries as $item)
                <div wire:key="industry-{{ $item->id }}" class="flex items-center justify-between gap-4 py-3">
                    <div class="flex items-center gap-3">
                        <span class="text-sm text-zinc-400">{{ $item->order }}</span>
                        <span class="font-medium">{{ $item->getTranslation('name', $editLocale) }}</span>
                        @unless ($item->is_published)
                            <flux:badge size="sm" color="amber">Entwurf</flux:badge>
                        @endunless
                    </div>
                    <div class="flex items-center gap-1">
                        <flux:button size="sm" variant="ghost" icon="chevron-up"
                            wire:click="moveUp({{ $item->id }})"
                            :disabled="$loop->first" />
                        <flux:button size="sm" variant="ghost" icon="chevron-down"
                            wire:click="moveDown({{ $item->id }})"
                            :disabled="$loop->last" />
                        <flux:button size="sm" variant="ghost" icon="pencil" wire:click="edit({{ $item->id }})" />
                        <flux:button size="sm" variant="ghost" :icon="$item->is_published ? 'eye' : 'eye-slash'" wire:click="togglePublished({{ $item->id }})" />
                        <flux:button size="sm" variant="ghost" icon="trash" wire:click="delete({{ $item->id }})" wire:confirm="Wirklich löschen?" />
                    </div>
                </div>
            @empty
                <flux:text class="py-8 text-center">Keine Industries vorhanden.</flux:text>
            @endforelse
        </div>
    </flux:card>
</div>
