<?php

namespace App\Livewire\Website;

use App\Domain\Shared\Exceptions\DomainException;
use App\Domain\Website\Models\WebsitePage;
use App\Domain\Website\Services\WebsitePageService;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\WithPagination;

class PageManager extends Component
{
    use WithPagination;

    #[Url]
    public string $search = '';

    #[Url]
    public string $status = '';

    #[Url]
    public string $sortBy = 'sort_order';

    #[Url]
    public string $sortDir = 'asc';

    public bool $showForm = false;

    public ?int $editingId = null;

    public string $title = '';

    public string $title_en = '';

    public string $slug = '';

    public string $layout = 'default';

    public string $meta_description = '';

    public bool $is_published = false;

    public bool $is_homepage = false;

    public function mount(): void
    {
        $this->authorize('settings.manage');
    }

    public function updatedSearch(): void
    {
        $this->resetPage();
    }

    public function updatedStatus(): void
    {
        $this->resetPage();
    }

    protected function rules(): array
    {
        return [
            'title' => 'required|string|max:255',
            'title_en' => 'nullable|string|max:255',
            'slug' => 'nullable|string|max:160|regex:/^[a-z0-9\-\/]*$/',
            'layout' => 'required|in:default,full_width,narrow,blank,landing',
            'meta_description' => 'nullable|string|max:320',
        ];
    }

    protected function messages(): array
    {
        return [
            'title.required' => __('اسم الصفحة مطلوب'),
            'title.max' => __('اسم الصفحة طويل جدًا'),
            'slug.regex' => __('الرابط يجب أن يحتوي على حروف إنجليزية صغيرة وأرقام وشرطات فقط'),
            'layout.required' => __('التخطيط مطلوب'),
            'layout.in' => __('التخطيط المختار غير صالح'),
            'meta_description.max' => __('وصف الصفحة طويل جدًا'),
        ];
    }

    public function create(): void
    {
        $this->resetForm();
        $this->showForm = true;
    }

    public function edit(int $id): void
    {
        $page = WebsitePage::findOrFail($id);

        $this->editingId = $page->id;
        $this->title = $page->title ?? '';
        $this->title_en = $page->title_en ?? '';
        $this->slug = $page->slug;
        $this->layout = $page->layout;
        $this->meta_description = $page->meta_description ?? '';
        $this->is_published = $page->is_published;
        $this->is_homepage = $page->is_homepage;
        $this->showForm = true;
    }

    public function save(WebsitePageService $service): void
    {
        $this->authorize('settings.manage');
        $data = $this->validate();

        $data['is_published'] = $this->is_published;
        $data['is_homepage'] = $this->is_homepage;

        try {
            if ($this->editingId) {
                $service->update(WebsitePage::findOrFail($this->editingId), $data);
                session()->flash('success', __('تم تحديث الصفحة'));
            } else {
                $page = $service->create($data, auth()->user());
                session()->flash('success', __('تم إنشاء الصفحة'));
                $this->redirectRoute('website.manage.builder', ['page' => $page->id], navigate: true);

                return;
            }

            $this->showForm = false;
            $this->resetForm();
        } catch (DomainException $e) {
            $this->addError('title', $e->getMessage());
        }
    }

    public function duplicate(int $id, WebsitePageService $service): void
    {
        $this->authorize('settings.manage');

        try {
            $service->duplicate(WebsitePage::findOrFail($id), auth()->user());
            session()->flash('success', __('تم نسخ الصفحة'));
        } catch (DomainException $e) {
            session()->flash('error', $e->getMessage());
        }
    }

    public function makeHomepage(int $id, WebsitePageService $service): void
    {
        $this->authorize('settings.manage');
        $service->makeHomepage(WebsitePage::findOrFail($id));
        session()->flash('success', __('تم تعيين الصفحة كصفحة رئيسية'));
    }

    public function togglePublish(int $id, WebsitePageService $service): void
    {
        $this->authorize('settings.manage');
        $page = WebsitePage::findOrFail($id);

        try {
            $service->update($page, ['is_published' => ! $page->is_published]);
        } catch (DomainException $e) {
            session()->flash('error', $e->getMessage());
        }
    }

    public function delete(int $id, WebsitePageService $service): void
    {
        $this->authorize('settings.manage');

        try {
            $service->delete(WebsitePage::findOrFail($id));
            session()->flash('success', __('تم حذف الصفحة'));
        } catch (DomainException $e) {
            session()->flash('error', $e->getMessage());
        }
    }

    public function sort(string $column): void
    {
        $this->sortDir = ($this->sortBy === $column && $this->sortDir === 'asc') ? 'desc' : 'asc';
        $this->sortBy = $column;
    }

    private function resetForm(): void
    {
        $this->reset(['editingId', 'title', 'title_en', 'slug', 'meta_description', 'is_published', 'is_homepage']);
        $this->layout = 'default';
        $this->resetErrorBag();
    }

    public function render()
    {
        $pages = WebsitePage::query()
            ->when($this->search, fn ($q) => $q->where(fn ($w) => $w
                ->where('title', 'ilike', "%{$this->search}%")
                ->orWhere('title_en', 'ilike', "%{$this->search}%")
                ->orWhere('slug', 'ilike', "%{$this->search}%")))
            ->when($this->status === 'published', fn ($q) => $q->where('is_published', true))
            ->when($this->status === 'draft', fn ($q) => $q->where('is_published', false))
            ->withCount('allBlocks')
            ->orderBy($this->sortBy, $this->sortDir)
            ->paginate(15);

        return view('livewire.website.page-manager', compact('pages'));
    }
}
