<?php

namespace App\Livewire\Website;

use App\Domain\Website\Enums\SectionKey;
use App\Domain\Website\Models\WebsiteSection;
use App\Domain\Website\Models\WebsiteSetting;
use App\Domain\Website\Services\WebsiteSectionService;
use App\Domain\Website\Services\WebsiteSettingService;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Layout('layouts.app')]
#[Title('إدارة الموقع الإلكتروني')]
class SectionManager extends Component
{
    public array $sections = [];
    public ?string $editingSection = null;

    // Section form fields
    public string $sectionTitle = '';
    public string $sectionTitleEn = '';
    public string $sectionSubtitle = '';
    public string $sectionSubtitleEn = '';
    public string $sectionContent = '';
    public string $sectionContentEn = '';
    public array $sectionSettings = [];

    public bool $isPublished = false;

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

        $academy = app('current_academy');
        $sectionService = app(WebsiteSectionService::class);
        $sectionService->seedDefaults($academy);

        $this->loadSections();

        $settings = app(WebsiteSettingService::class)->getOrCreate($academy);
        $this->isPublished = $settings->is_published;
    }

    public function loadSections(): void
    {
        $academy = app('current_academy');
        $this->sections = WebsiteSection::withoutGlobalScope('academy')
            ->where('academy_id', $academy->id)
            ->orderBy('sort_order')
            ->get()
            ->map(fn ($s) => [
                'id' => $s->id,
                'key' => $s->section_key->value,
                'label' => $s->section_key->label(),
                'icon' => $s->section_key->icon(),
                'title' => $s->title,
                'is_enabled' => $s->is_enabled,
                'sort_order' => $s->sort_order,
            ])
            ->toArray();
    }

    public function toggleSection(int $id): void
    {
        $section = WebsiteSection::find($id);
        if ($section) {
            app(WebsiteSectionService::class)->toggle($section, !$section->is_enabled);
            $this->loadSections();
        }
    }

    public function reorder(array $orderedIds): void
    {
        $academy = app('current_academy');
        foreach ($orderedIds as $index => $id) {
            WebsiteSection::where('id', $id)->update(['sort_order' => $index]);
        }
        app(\App\Domain\Website\Services\WebsiteCacheService::class)->invalidate($academy->id);
        $this->loadSections();
    }

    public function editSection(string $key): void
    {
        $academy = app('current_academy');
        $section = WebsiteSection::withoutGlobalScope('academy')
            ->where('academy_id', $academy->id)
            ->where('section_key', $key)
            ->first();

        if ($section) {
            $this->editingSection = $key;
            $this->sectionTitle = $section->title ?? '';
            $this->sectionTitleEn = $section->title_en ?? '';
            $this->sectionSubtitle = $section->subtitle ?? '';
            $this->sectionSubtitleEn = $section->subtitle_en ?? '';
            $this->sectionContent = $section->content ?? '';
            $this->sectionContentEn = $section->content_en ?? '';
            $this->sectionSettings = $section->settings ?? [];
        }
    }

    public function saveSection(): void
    {
        $academy = app('current_academy');
        $section = WebsiteSection::withoutGlobalScope('academy')
            ->where('academy_id', $academy->id)
            ->where('section_key', $this->editingSection)
            ->first();

        if ($section) {
            app(WebsiteSectionService::class)->updateContent($section, [
                'title' => $this->sectionTitle,
                'title_en' => $this->sectionTitleEn,
                'subtitle' => $this->sectionSubtitle,
                'subtitle_en' => $this->sectionSubtitleEn,
                'content' => $this->sectionContent,
                'content_en' => $this->sectionContentEn,
                'settings' => $this->sectionSettings,
            ]);

            $this->loadSections();
            session()->flash('success', __('تم حفظ القسم بنجاح'));
        }
    }

    public function cancelEdit(): void
    {
        $this->editingSection = null;
    }

    public function publish(): void
    {
        $academy = app('current_academy');
        app(WebsiteSettingService::class)->publish($academy);
        $this->isPublished = true;
        session()->flash('success', __('تم نشر الموقع بنجاح'));
    }

    public function unpublish(): void
    {
        $academy = app('current_academy');
        app(WebsiteSettingService::class)->unpublish($academy);
        $this->isPublished = false;
        session()->flash('success', __('تم إلغاء نشر الموقع'));
    }

    public function render()
    {
        return view('livewire.website.section-manager');
    }
}
