<?php

namespace App\Filament\Resources\LandingPages\Pages;

use App\Filament\Resources\LandingPageResource;
use Filament\Resources\Pages\ListRecords;
use Pboivin\FilamentPeek\Pages\Concerns\HasPreviewModal;
use Pboivin\FilamentPeek\Pages\Concerns\HasBuilderPreview;

class ListLandingPages extends ListRecords
{
    use HasPreviewModal;
    use HasBuilderPreview;

    protected static string $resource = LandingPageResource::class;

    public function booted(): void
    {
        \Pboivin\FilamentPeek\Facades\Peek::registerPreviewModal();
        \Pboivin\FilamentPeek\Facades\Peek::registerBuilderEditor();
    }

    protected function getHeaderActions(): array
    {
        return [
            //
        ];
    }

    protected function getPreviewModalView(): ?string
    {
        return 'landing.preview';
    }

    protected function getBuilderPreviewView(string $builderName): ?string
    {
        return 'landing.preview';
    }

    public static function getBuilderEditorSchema(string $builderName): \Filament\Schemas\Components\Component|array
    {
        if ($builderName === 'sections_builder') {
            return [
                \Filament\Schemas\Components\Section::make('General Settings')
                    ->schema(\App\Filament\Resources\LandingPages\Schemas\LandingPageForm::getGeneralSchema())
                    ->collapsed(),
                \Filament\Schemas\Components\Section::make('Linked Product & Pricing')
                    ->schema(\App\Filament\Resources\LandingPages\Schemas\LandingPageForm::getProductSchema())
                    ->collapsed(),
                \Filament\Schemas\Components\Section::make('Design & Theme')
                    ->schema(\App\Filament\Resources\LandingPages\Schemas\LandingPageForm::getDesignSchema())
                    ->collapsed(),
                \App\Filament\Resources\LandingPages\Schemas\LandingPageForm::getSectionsBuilder(),
            ];
        }
        return [];
    }

    public function openPreviewModalForBuilder(string $builderName): void
    {
        $recordId = session('peek_active_record_id');
        $record = \App\Models\LandingPage::with('sections')->find($recordId);

        if (!$record) {
            return;
        }

        // Build the initial editorData manually from the database record
        $editorData = [
            'title' => $record->title,
            'slug' => $record->slug,
            'is_active' => $record->is_active,
            'product_id' => $record->product_id,
            'landing_price' => $record->landing_price,
            'fb_pixel_id' => $record->fb_pixel_id,
            'template_style' => $record->template_style,
            'font_family' => $record->font_family,
            'primary_color' => $record->primary_color,
            'secondary_color' => $record->secondary_color,
            'gradient_angle' => $record->gradient_angle,
            'sections_builder' => $record->sections->map(function ($section) {
                return [
                    'type' => $section->block_type,
                    'data' => $section->content,
                ];
            })->toArray(),
        ];

        $this->dispatch(
            'openBuilderEditor',
            previewView: 'landing.preview',
            previewUrl: null,
            modalTitle: 'Live Visual Editor',
            editorTitle: 'Live Visual Editor',
            editorData: $editorData,
            builderName: $builderName,
            pageClass: static::class,
        );
    }

    public static function mutateBuilderPreviewData(string $builderName, array $editorData, array $previewData): array
    {
        $recordId = session('peek_active_record_id');
        $record = \App\Models\LandingPage::with('product')->find($recordId);

        if ($record) {
            if (isset($editorData['title'])) {
                $record->title = $editorData['title'];
            }
            if (isset($editorData['slug'])) {
                $record->slug = $editorData['slug'];
            }
            if (isset($editorData['template_style'])) {
                $record->template_style = $editorData['template_style'];
            }
            if (isset($editorData['primary_color'])) {
                $record->primary_color = $editorData['primary_color'];
            }
            if (isset($editorData['secondary_color'])) {
                $record->secondary_color = $editorData['secondary_color'];
            }
            if (isset($editorData['font_family'])) {
                $record->font_family = $editorData['font_family'];
            }
            if (isset($editorData['gradient_angle'])) {
                $record->gradient_angle = $editorData['gradient_angle'];
            }
            if (isset($editorData['landing_price'])) {
                $record->landing_price = $editorData['landing_price'];
            }
            if (isset($editorData['product_id'])) {
                $record->product_id = $editorData['product_id'];
                $record->load('product');
            }
        }

        $tempSections = $editorData['sections_builder'] ?? [];

        $sections = collect($tempSections)->map(function ($block, $index) {
            return (object) [
                'block_type' => $block['type'],
                'content' => $block['data'],
                'sort_order' => $index,
            ];
        });

        return [
            'page' => $record,
            'product' => $record?->product,
            'sections' => $sections,
        ];
    }

    public function updateBuilderFieldWithEditorData(string $builderName, array $editorData): void
    {
        $recordId = session('peek_active_record_id');
        $record = \App\Models\LandingPage::find($recordId);

        if ($record) {
            $record->update([
                'title' => $editorData['title'] ?? $record->title,
                'slug' => $editorData['slug'] ?? $record->slug,
                'is_active' => $editorData['is_active'] ?? $record->is_active,
                'product_id' => $editorData['product_id'] ?? $record->product_id,
                'landing_price' => $editorData['landing_price'] ?? $record->landing_price,
                'fb_pixel_id' => $editorData['fb_pixel_id'] ?? $record->fb_pixel_id,
                'template_style' => $editorData['template_style'] ?? $record->template_style,
                'font_family' => $editorData['font_family'] ?? $record->font_family,
                'primary_color' => $editorData['primary_color'] ?? $record->primary_color,
                'secondary_color' => $editorData['secondary_color'] ?? $record->secondary_color,
                'gradient_angle' => $editorData['gradient_angle'] ?? $record->gradient_angle,
            ]);

            // Save sections blocks
            $record->sections()->delete();
            $tempSections = $editorData['sections_builder'] ?? [];
            $sortOrder = 0;
            foreach ($tempSections as $block) {
                $record->sections()->create([
                    'block_type' => $block['type'],
                    'content' => $block['data'],
                    'sort_order' => $sortOrder++,
                ]);
            }

            \Filament\Notifications\Notification::make()
                ->title('Landing page saved successfully!')
                ->success()
                ->send();
        }

        // Close preview modal
        $this->dispatch('close-preview-modal');
    }
}
