<?php

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

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

state([
    'editLocale' => 'de',
    'showForm' => false,
    'editingId' => null,
    'title' => '',
    'excerpt' => '',
    'content' => '',
    'author' => '',
    'date' => null,
    'url' => '',
    'image' => '',
    'imageMediaId' => null,
    'tags' => '',
    'source' => 'manual',
]);

$posts = computed(fn() => CmsLinkedinPost::ordered()->get());

$create = function () {
    $this->reset(['editingId', 'title', 'excerpt', 'content', 'author', 'date', 'url', 'image', 'imageMediaId', 'tags', 'source']);
    $this->source = 'manual';
    $this->showForm = true;
};

$edit = function (int $id) {
    $post = CmsLinkedinPost::findOrFail($id);
    $this->editingId = $id;
    $this->showForm = true;
    $l = $this->editLocale;
    $this->title = $post->getTranslation('title', $l) ?? '';
    $this->excerpt = $post->getTranslation('excerpt', $l) ?? '';
    $this->content = $post->getTranslation('content', $l) ?? '';
    $this->author = $post->author ?? '';
    $this->date = $post->date?->format('Y-m-d');
    $this->url = $post->url ?? '';
    $this->image = $post->image ?? '';
    $this->imageMediaId = $this->image ? \FluxCms\Core\Models\CmsMedia::where('filename', $this->image)->first()?->id : null;
    $this->tags = is_array($post->tags) ? implode(', ', $post->tags) : '';
    $this->source = $post->source;
};

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

    $mergeT = function (string $field, string $value) use ($existing) {
        $t = $existing ? $existing->getTranslations($field) : [];
        $t[$this->editLocale] = $value;
        return $t;
    };

    $tagsArray = array_map('trim', explode(',', $this->tags));
    $tagsArray = array_filter($tagsArray);

    $data = [
        'title' => $mergeT('title', $this->title),
        'excerpt' => $mergeT('excerpt', $this->excerpt),
        'content' => $mergeT('content', $this->content),
        'author' => $this->author,
        'date' => $this->date ?: null,
        'url' => $this->url,
        'image' => $this->image,
        'tags' => array_values($tagsArray),
        'source' => $this->source,
    ];

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

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

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

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

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

$switchLocale = function (string $locale) {
    $this->editLocale = $locale;
    if ($this->editingId) {
        $post = CmsLinkedinPost::find($this->editingId);
        if ($post) {
            $this->title = $post->getTranslation('title', $locale) ?? '';
            $this->excerpt = $post->getTranslation('excerpt', $locale) ?? '';
            $this->content = $post->getTranslation('content', $locale) ?? '';
        }
    }
};

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

on(['media-selected' => function (string $field, ?int $mediaId, ?string $url) {
    if ($field === 'linkedin_image') {
        $this->imageMediaId = $mediaId;
        $media = $mediaId ? \FluxCms\Core\Models\CmsMedia::find($mediaId) : null;
        $this->image = $media ? $media->filename : '';
    }
}]);

?>

<div>
    <div class="mb-6 flex items-center justify-between">
        <flux:heading size="xl">LinkedIn Beiträge</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' : 'Neuer LinkedIn Beitrag' }}
            </flux:heading>
            <div class="grid grid-cols-1 gap-4 md:grid-cols-2">
                <flux:input wire:model="title" label="Titel" />
                <flux:input wire:model="author" label="Autor" />
                <flux:input wire:model="date" label="Datum" type="date" />
                <flux:input wire:model="url" label="LinkedIn URL" />
                <div>
                    <label class="mb-1 block text-sm font-medium">Bild</label>
                    <div class="flex items-start gap-3">
                        @if ($image)
                            <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($image) }}" class="h-full w-full object-cover" />
                            </div>
                        @endif
                        <div class="flex-1">
                            <livewire:admin.cms.media-picker
                                :value="$imageMediaId"
                                field="linkedin_image"
                                type="image"
                                profile="news"
                                label="Bild wählen"
                                :key="'linkedin-img-' . ($editingId ?? 'new')" />
                            <p class="mt-1 text-xs text-zinc-400">{{ $image ?: 'Kein Bild' }}</p>
                        </div>
                    </div>
                </div>
                <flux:input wire:model="tags" label="Tags (kommagetrennt)" />
                <flux:select wire:model="source" label="Quelle">
                    <flux:select.option value="manual">Manuell</flux:select.option>
                    <flux:select.option value="api">API</flux:select.option>
                </flux:select>
            </div>
            <div class="mt-4">
                <flux:editor wire:model="excerpt" label="Kurztext" toolbar="bold italic"
                    class="**:data-[slot=content]:min-h-[60px]!" />
            </div>
            <div class="mt-4">
                <flux:editor wire:model="content" label="Inhalt"
                    toolbar="bold italic"
                    class="**:data-[slot=content]:min-h-[120px]!" />
            </div>
            <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->posts as $post)
                <div wire:key="linkedin-{{ $post->id }}" class="flex items-center justify-between gap-4 py-3">
                    <div class="flex min-w-0 flex-1 items-center gap-3">
                        @if ($post->image)
                            <div class="h-10 w-10 shrink-0 overflow-hidden rounded-lg bg-zinc-100 dark:bg-zinc-700">
                                <img src="{{ media_url($post->image) }}" alt="" class="h-full w-full object-cover" />
                            </div>
                        @endif
                        <div class="min-w-0">
                        <div class="flex items-center gap-2">
                            <span class="font-medium">{{ $post->getTranslation('title', $editLocale) }}</span>
                            <flux:badge size="sm" :color="$post->source === 'api' ? 'blue' : 'zinc'">
                                {{ $post->source }}</flux:badge>
                            @unless ($post->is_published)
                                <flux:badge size="sm" color="amber">Entwurf</flux:badge>
                            @endunless
                        </div>
                        <p class="text-sm text-zinc-600 dark:text-zinc-400">{{ $post->author }} ·
                            {{ $post->date?->format('d.m.Y') }}</p>
                    </div></div>
                    <div class="flex items-center gap-1">
                        <flux:button size="sm" variant="ghost" icon="pencil"
                            wire:click="edit({{ $post->id }})" />
                        <flux:button size="sm" variant="ghost" :icon="$post->is_published ? 'eye' : 'eye-slash'"
                            wire:click="togglePublished({{ $post->id }})" />
                        <flux:button size="sm" variant="ghost" icon="trash"
                            wire:click="delete({{ $post->id }})" wire:confirm="Wirklich löschen?" />
                    </div>
                </div>
            @empty
                <flux:text class="py-8 text-center">Keine LinkedIn Beiträge vorhanden.</flux:text>
            @endforelse
        </div>
    </flux:card>
</div>
