<?php

use App\Models\CommunityPost;
use App\Traits\Vrm\Livewire\WithNotifications;
use Livewire\Attributes\Locked;
use Livewire\Component;

new class extends Component {
    use WithNotifications;

    #[Locked]
    public int $postId;

    public string $title = '';
    public string $body_html = '';
    public bool $is_active = true;
    public ?string $published_at = null;

    public function mount(int $post): void
    {
        $communityPost = CommunityPost::query()->findOrFail($post);

        $this->postId = $communityPost->id;
        $this->title = $communityPost->title;
        $this->body_html = $communityPost->body_html;
        $this->is_active = (bool) $communityPost->is_active;
        $this->published_at = $communityPost->published_at?->format('Y-m-d\\TH:i');
    }

    public function save(): void
    {
        $validated = $this->validate([
            'title' => ['required', 'string', 'max:255'],
            'body_html' => ['required', 'string', 'min:2'],
            'is_active' => ['required', 'boolean'],
            'published_at' => ['nullable', 'date'],
        ]);

        CommunityPost::query()->findOrFail($this->postId)->update([
            'title' => $validated['title'],
            'body_html' => $validated['body_html'],
            'is_active' => $validated['is_active'],
            'published_at' => $validated['published_at'],
        ]);

        $this->notifySuccess(__('Community post updated successfully.'));
    }
}; ?>

<div>
    <x-admin-panel>
        <x-slot name="header">{{ __('Edit Community Post') }}</x-slot>
        <x-slot name="desc">{{ __('Update content and publication state for this post.') }}</x-slot>
        <x-slot name="button">
            <a href="{{ route('admin.community.index') }}" wire:navigate
                class="rounded-md border border-gray-300 px-3 py-2 text-sm font-semibold text-gray-700 hover:bg-gray-100 dark:border-gray-600 dark:text-gray-100 dark:hover:bg-gray-700">
                {{ __('Back to posts') }}
            </a>
        </x-slot>

        {!! $this->renderNotification() !!}

        <form wire:submit="save" class="space-y-4">
            <div>
                <label for="community-title" class="mb-1 block text-sm font-semibold text-gray-900 dark:text-gray-100">{{ __('Title') }}</label>
                <input id="community-title" type="text" wire:model="title"
                    class="block w-full rounded-md border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900 outline-none focus:border-indigo-500 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-100" />
                @error('title')
                    <p class="mt-1 text-xs text-red-500">{{ $message }}</p>
                @enderror
            </div>

            <div>
                <label for="community-published-at" class="mb-1 block text-sm font-semibold text-gray-900 dark:text-gray-100">{{ __('Publication Date') }}</label>
                <input id="community-published-at" type="datetime-local" wire:model="published_at"
                    class="block w-full rounded-md border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900 outline-none focus:border-indigo-500 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-100" />
                @error('published_at')
                    <p class="mt-1 text-xs text-red-500">{{ $message }}</p>
                @enderror
            </div>

            <div>
                <label class="inline-flex items-center gap-2 text-sm font-medium text-gray-900 dark:text-gray-100">
                    <input type="checkbox" wire:model="is_active" class="rounded border-gray-300 text-indigo-600 focus:ring-indigo-500" />
                    <span>{{ __('Enable post') }}</span>
                </label>
            </div>

            <div>
                <label class="mb-1 block text-sm font-semibold text-gray-900 dark:text-gray-100">{{ __('Content (WYSIWYG)') }}</label>
                <div class="rounded-md border border-gray-300 dark:border-gray-600">
                    <div class="flex flex-wrap gap-2 border-b border-gray-300 p-2 dark:border-gray-600">
                        <button type="button" data-wysiwyg-action="bold" class="rounded bg-gray-100 px-2 py-1 text-xs font-semibold text-gray-700 hover:bg-gray-200 dark:bg-gray-700 dark:text-gray-100">B</button>
                        <button type="button" data-wysiwyg-action="italic" class="rounded bg-gray-100 px-2 py-1 text-xs font-semibold text-gray-700 hover:bg-gray-200 dark:bg-gray-700 dark:text-gray-100">I</button>
                        <button type="button" data-wysiwyg-action="insertUnorderedList" class="rounded bg-gray-100 px-2 py-1 text-xs font-semibold text-gray-700 hover:bg-gray-200 dark:bg-gray-700 dark:text-gray-100">• {{ __('List') }}</button>
                    </div>
                    <div id="community-editor" contenteditable="true" wire:ignore
                        class="min-h-52 w-full bg-white px-3 py-2 text-sm text-gray-900 focus:outline-none dark:bg-gray-700 dark:text-gray-100">{!! $body_html !!}</div>
                </div>
                <input type="hidden" wire:model="body_html" id="community-body-input" />
                @error('body_html')
                    <p class="mt-1 text-xs text-red-500">{{ $message }}</p>
                @enderror
            </div>

            <div class="pt-2">
                <button type="submit"
                    class="inline-flex items-center rounded-md bg-indigo-600 px-4 py-2 text-sm font-semibold text-white hover:bg-indigo-500">
                    {{ __('Save Changes') }}
                </button>
            </div>
        </form>
    </x-admin-panel>

    @script
        <script>
            const editor = document.getElementById('community-editor');
            const input = document.getElementById('community-body-input');

            const syncEditor = () => {
                input.value = editor.innerHTML;
                input.dispatchEvent(new Event('input', {
                    bubbles: true
                }));
            };

            syncEditor();

            editor.addEventListener('input', syncEditor);

            document.querySelectorAll('[data-wysiwyg-action]').forEach((button) => {
                button.addEventListener('click', () => {
                    document.execCommand(button.dataset.wysiwygAction, false);
                    editor.focus();
                    syncEditor();
                });
            });
        </script>
    @endscript
</div>
