<?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 = [];

    // Hero variant & layout
    public string $heroVariant = 'fullscreen';
    public string $sectionLayout = 'grid_3';

    // Section visual controls
    public string $sectionBgType = 'inherit';
    public string $sectionBgColor = '#ffffff';
    public string $sectionBgGradientFrom = '#1a1a2e';
    public string $sectionBgGradientTo = '#16213e';
    public int $sectionBgGradientAngle = 180;
    public int $sectionBgOverlayOpacity = 60;
    public string $sectionAnimation = 'fade-up';
    public string $sectionPaddingY = 'inherit';
    public bool $sectionHiddenOnMobile = false;

    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 moveSection(int $id, string $direction): void
    {
        $currentIndex = collect($this->sections)->search(fn($s) => $s['id'] === $id);
        if ($currentIndex === false) return;

        $targetIndex = $direction === 'up' ? $currentIndex - 1 : $currentIndex + 1;
        if ($targetIndex < 0 || $targetIndex >= count($this->sections)) return;

        $currentId = $this->sections[$currentIndex]['id'];
        $targetId = $this->sections[$targetIndex]['id'];

        WebsiteSection::where('id', $currentId)->update(['sort_order' => $targetIndex]);
        WebsiteSection::where('id', $targetId)->update(['sort_order' => $currentIndex]);

        app(\App\Domain\Website\Services\WebsiteCacheService::class)->invalidate(app('current_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 ?? [];
            $this->heroVariant = $section->getSetting('variant', 'fullscreen');
            $this->sectionLayout = $section->getSetting('layout', 'grid_3');
            $this->sectionBgType = $section->bg_type ?? 'inherit';
            $this->sectionBgColor = $section->bg_color ?? '#ffffff';
            $this->sectionBgGradientFrom = $section->bg_gradient_from ?? '#1a1a2e';
            $this->sectionBgGradientTo = $section->bg_gradient_to ?? '#16213e';
            $this->sectionBgGradientAngle = $section->bg_gradient_angle ?? 180;
            $this->sectionBgOverlayOpacity = $section->bg_overlay_opacity ?? 60;
            $this->sectionAnimation = $section->animation ?? 'fade-up';
            $this->sectionPaddingY = $section->padding_y ?? 'inherit';
            $this->sectionHiddenOnMobile = $section->hidden_on_mobile ?? false;
        }
    }

    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) {
            $settings = $this->sectionSettings;

            if ($this->editingSection === 'hero') {
                $settings['variant'] = $this->heroVariant;
            }

            $layoutSections = ['activities', 'programs', 'trainers', 'news', 'branches', 'testimonials', 'events'];
            if (in_array($this->editingSection, $layoutSections)) {
                $settings['layout'] = $this->sectionLayout;
            }

            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' => $settings,
            ]);

            $section->update([
                'bg_type' => $this->sectionBgType,
                'bg_color' => $this->sectionBgType === 'solid' ? $this->sectionBgColor : null,
                'bg_gradient_from' => $this->sectionBgType === 'gradient' ? $this->sectionBgGradientFrom : null,
                'bg_gradient_to' => $this->sectionBgType === 'gradient' ? $this->sectionBgGradientTo : null,
                'bg_gradient_angle' => $this->sectionBgGradientAngle,
                'bg_overlay_opacity' => $this->sectionBgOverlayOpacity,
                'animation' => $this->sectionAnimation,
                'padding_y' => $this->sectionPaddingY,
                'hidden_on_mobile' => $this->sectionHiddenOnMobile,
            ]);

            $this->loadSections();
            $this->editingSection = null;
            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');
    }
}
