<?php

namespace FluxCms\Components\Livewire\Backend;

use FluxCms\Core\Models\BlogPost;
use Livewire\Component;
use Livewire\WithPagination;

class BlogManager extends Component
{
    use WithPagination;

    public string $domainKey;

    public array $availableLanguages = [];

    public string $currentLocale = 'de';

    public string $search = '';

    public string $filterStatus = 'all';

    public bool $showCreateModal = false;

    public ?BlogPost $editingPost = null;

    // Form data
    public array $postData = [];

    protected $paginationTheme = 'simple-bootstrap';

    public function mount(string $domainKey)
    {
        $this->domainKey = $domainKey;
        $this->availableLanguages = array_keys(config('flux-cms.locales', ['de' => 'Deutsch', 'en' => 'English']));
        $this->currentLocale = app()->getLocale();
    }

    public function render()
    {
        $posts = $this->getFilteredPosts();

        return view('flux-cms-components::livewire.backend.blog-manager', [
            'posts' => $posts,
        ])->layout('flux-cms-components::layouts.admin');
    }

    /**
     * Get filtered blog posts
     */
    protected function getFilteredPosts()
    {
        $query = BlogPost::forDomain($this->domainKey);

        // Search filter
        if (! empty($this->search)) {
            $query->where(function ($q) {
                $q->where('title->de', 'like', '%'.$this->search.'%')
                    ->orWhere('title->en', 'like', '%'.$this->search.'%')
                    ->orWhere('content->de', 'like', '%'.$this->search.'%')
                    ->orWhere('content->en', 'like', '%'.$this->search.'%');
            });
        }

        // Status filter
        if ($this->filterStatus === 'published') {
            $query->published();
        } elseif ($this->filterStatus === 'draft') {
            $query->where('is_published', false);
        } elseif ($this->filterStatus === 'featured') {
            $query->featured();
        }

        return $query->orderBy('updated_at', 'desc')->paginate(15);
    }

    /**
     * Switch locale
     */
    public function switchLocale(string $locale)
    {
        if (in_array($locale, $this->availableLanguages)) {
            $this->currentLocale = $locale;
        }
    }

    /**
     * Search updated
     */
    public function updatedSearch()
    {
        $this->resetPage();
    }

    /**
     * Filter updated
     */
    public function updatedFilterStatus()
    {
        $this->resetPage();
    }

    /**
     * Show create modal
     */
    public function showCreatePost()
    {
        $this->editingPost = null;
        $this->postData = [
            'title' => array_fill_keys($this->availableLanguages, ''),
            'slug' => array_fill_keys($this->availableLanguages, ''),
            'excerpt' => array_fill_keys($this->availableLanguages, ''),
            'content' => array_fill_keys($this->availableLanguages, ''),
            'meta_description' => array_fill_keys($this->availableLanguages, ''),
            'meta_keywords' => array_fill_keys($this->availableLanguages, ''),
            'is_published' => false,
            'is_featured' => false,
            'published_at' => null,
        ];
        $this->showCreateModal = true;
    }

    /**
     * Edit post
     */
    public function editPost(int $postId)
    {
        $this->editingPost = BlogPost::findOrFail($postId);
        $this->postData = [
            'title' => $this->editingPost->getTranslations('title'),
            'slug' => $this->editingPost->getTranslations('slug'),
            'excerpt' => $this->editingPost->getTranslations('excerpt'),
            'content' => $this->editingPost->getTranslations('content'),
            'meta_description' => $this->editingPost->getTranslations('meta_description'),
            'meta_keywords' => $this->editingPost->getTranslations('meta_keywords'),
            'is_published' => $this->editingPost->is_published,
            'is_featured' => $this->editingPost->is_featured,
            'published_at' => $this->editingPost->published_at?->format('Y-m-d\TH:i'),
        ];
        $this->showCreateModal = true;
    }

    /**
     * Save post
     */
    public function savePost()
    {
        $this->validate([
            'postData.title' => 'required|array',
            'postData.slug' => 'required|array',
            'postData.content' => 'required|array',
        ]);

        try {
            $data = [
                'domain_key' => $this->domainKey,
                'title' => $this->postData['title'],
                'slug' => $this->postData['slug'],
                'excerpt' => $this->postData['excerpt'],
                'content' => $this->postData['content'],
                'meta_description' => $this->postData['meta_description'],
                'meta_keywords' => $this->postData['meta_keywords'],
                'is_published' => $this->postData['is_published'] ?? false,
                'is_featured' => $this->postData['is_featured'] ?? false,
                'published_at' => $this->postData['published_at'] ?
                    \Carbon\Carbon::parse($this->postData['published_at']) : null,
            ];

            if ($this->editingPost) {
                $this->editingPost->update($data);
                $message = 'Blog post updated successfully.';
            } else {
                $data['author_id'] = auth()->id();
                BlogPost::create($data);
                $message = 'Blog post created successfully.';
            }

            $this->showCreateModal = false;
            $this->resetPage();
            session()->flash('success', $message);

        } catch (\Exception $e) {
            session()->flash('error', 'Error saving blog post: '.$e->getMessage());
        }
    }

    /**
     * Delete post
     */
    public function deletePost(int $postId)
    {
        try {
            $post = BlogPost::find($postId);
            if ($post) {
                $post->delete();
                session()->flash('success', 'Blog post deleted successfully.');
            }
        } catch (\Exception $e) {
            session()->flash('error', 'Error deleting blog post: '.$e->getMessage());
        }
    }

    /**
     * Toggle publish status
     */
    public function togglePublish(int $postId)
    {
        try {
            $post = BlogPost::find($postId);
            if ($post) {
                if ($post->is_published) {
                    $post->unpublish();
                    $message = 'Blog post unpublished.';
                } else {
                    $post->publish();
                    $message = 'Blog post published.';
                }
                session()->flash('success', $message);
            }
        } catch (\Exception $e) {
            session()->flash('error', 'Error updating publish status: '.$e->getMessage());
        }
    }

    /**
     * Toggle featured status
     */
    public function toggleFeatured(int $postId)
    {
        try {
            $post = BlogPost::find($postId);
            if ($post) {
                $post->update(['is_featured' => ! $post->is_featured]);
                $message = $post->is_featured ? 'Post marked as featured.' : 'Post removed from featured.';
                session()->flash('success', $message);
            }
        } catch (\Exception $e) {
            session()->flash('error', 'Error updating featured status: '.$e->getMessage());
        }
    }

    /**
     * Duplicate post
     */
    public function duplicatePost(int $postId)
    {
        try {
            $original = BlogPost::find($postId);
            if ($original) {
                $duplicate = $original->replicate();
                $duplicate->is_published = false;
                $duplicate->published_at = null;

                // Update title to indicate it's a copy
                $titles = $duplicate->getTranslations('title');
                foreach ($titles as $locale => $title) {
                    $titles[$locale] = $title.' (Copy)';
                }
                $duplicate->title = $titles;

                // Update slugs to avoid conflicts
                $slugs = $duplicate->getTranslations('slug');
                foreach ($slugs as $locale => $slug) {
                    $slugs[$locale] = $slug.'-copy-'.time();
                }
                $duplicate->slug = $slugs;

                $duplicate->save();
                session()->flash('success', 'Blog post duplicated successfully.');
            }
        } catch (\Exception $e) {
            session()->flash('error', 'Error duplicating blog post: '.$e->getMessage());
        }
    }

    /**
     * Generate slug from title
     */
    public function generateSlug(string $locale)
    {
        $title = $this->postData['title'][$locale] ?? '';
        if ($title) {
            $slug = \Illuminate\Support\Str::slug($title);
            $this->postData['slug'][$locale] = '/'.$slug;
        }
    }

    /**
     * Close modal
     */
    public function closeModal()
    {
        $this->showCreateModal = false;
        $this->editingPost = null;
        $this->postData = [];
    }

    /**
     * Get available filters
     */
    public function getAvailableFiltersProperty(): array
    {
        return [
            'all' => 'All Posts',
            'published' => 'Published',
            'draft' => 'Drafts',
            'featured' => 'Featured',
        ];
    }

    /**
     * Get post stats
     */
    public function getStatsProperty(): array
    {
        return [
            'total' => BlogPost::forDomain($this->domainKey)->count(),
            'published' => BlogPost::forDomain($this->domainKey)->published()->count(),
            'drafts' => BlogPost::forDomain($this->domainKey)->where('is_published', false)->count(),
            'featured' => BlogPost::forDomain($this->domainKey)->featured()->count(),
        ];
    }
}
