<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Page;
use App\Services\MediaUsageSyncService;
use Illuminate\Http\Request;

class PageController extends Controller
{
    public function index()
    {
        $pages = Page::orderBy('title')->get();

        return view('admin.pages.index', compact('pages'));
    }

    public function create()
    {
        return view('admin.pages.create');
    }

    public function store(Request $request, MediaUsageSyncService $mediaUsageSyncService)
    {
        $page = Page::create($this->validatedData($request, null));
        $mediaUsageSyncService->syncForPage($page);

        return redirect()->route('admin.pages.index')->with('success', 'Page created successfully.');
    }

    public function edit(Page $page)
    {
        return view('admin.pages.edit', compact('page'));
    }

    public function update(Request $request, Page $page, MediaUsageSyncService $mediaUsageSyncService)
    {
        $page->update($this->validatedData($request, $page));
        $mediaUsageSyncService->syncForPage($page);

        return redirect()->route('admin.pages.index')->with('success', 'Page updated successfully.');
    }

    public function destroy(Page $page)
    {
        $page->delete();

        return redirect()->route('admin.pages.index')->with('success', 'Page deleted successfully.');
    }

    protected function validatedData(Request $request, ?Page $page): array
    {
        $data = $request->validate([
            'title' => 'required|string|max:255',
            'slug' => 'required|string|max:255|unique:pages,slug,' . ($page?->id ?? 'NULL'),
            'template' => 'nullable|string|max:50',
            'content' => 'nullable|string',
            'sections' => 'nullable',
            'sections_json' => 'nullable|string',
            'meta_title' => 'nullable|string|max:255',
            'meta_description' => 'nullable|string',
        ]);

        $data['sections'] = $this->normalizeSections($request, $data['template'] ?? null);

        return $data;
    }

    protected function normalizeSections(Request $request, ?string $template): ?array
    {
        if (in_array($template, ['home', 'about', 'blog'], true) && is_array($request->input($template, null))) {
            return match ($template) {
                'home' => $this->normalizeHomeSections($request->input('home', [])),
                'about' => $this->normalizeAboutSections($request->input('about', [])),
                'blog' => $this->normalizeBlogSections($request->input('blog', [])),
                default => null,
            };
        }

        $jsonSections = $request->input('sections_json', $request->input('sections'));

        if (filled($jsonSections) && is_string($jsonSections)) {
            return json_decode((string) $jsonSections, true) ?: null;
        }

        return match ($template) {
            'home' => $this->normalizeHomeSections($request->input('home', [])),
            'about' => $this->normalizeAboutSections($request->input('about', [])),
            'blog' => $this->normalizeBlogSections($request->input('blog', [])),
            default => null,
        };
    }

    protected function normalizeHomeSections(array $home): array
    {
        $hero = $home['hero'] ?? [];
        $trusted = $home['trusted'] ?? [];
        $whyTracking = $home['why_tracking'] ?? [];
        $servicesIntro = $home['services_intro'] ?? [];
        $pricing = $home['pricing'] ?? [];
        $security = $home['security'] ?? [];
        $caseStudies = $home['case_studies'] ?? [];
        $contactOptions = $home['contact_options'] ?? [];
        $benefits = $home['benefits'] ?? [];
        $cta = $home['cta'] ?? [];

        return [
            'hero' => [
                'eyebrow' => trim((string) ($hero['eyebrow'] ?? '')),
                'eyebrow_highlight' => trim((string) ($hero['eyebrow_highlight'] ?? '')),
                'title_html' => trim((string) ($hero['title_html'] ?? '')),
                'description' => trim((string) ($hero['description'] ?? '')),
                'primary_cta_label' => trim((string) ($hero['primary_cta_label'] ?? '')),
                'primary_cta_url' => trim((string) ($hero['primary_cta_url'] ?? '')),
                'secondary_cta_label' => trim((string) ($hero['secondary_cta_label'] ?? '')),
                'secondary_cta_url' => trim((string) ($hero['secondary_cta_url'] ?? '')),
                'image_media_id' => filled($hero['image_media_id'] ?? null) ? (int) $hero['image_media_id'] : null,
                'platforms' => collect($hero['platforms'] ?? [])
                    ->map(fn ($item) => [
                        'label' => trim((string) ($item['label'] ?? '')),
                        'media_id' => filled($item['media_id'] ?? null) ? (int) $item['media_id'] : null,
                    ])
                    ->filter(fn (array $item): bool => filled($item['label']) || filled($item['media_id']))
                    ->values()
                    ->all(),
            ],
            'trusted' => [
                'title' => trim((string) ($trusted['title'] ?? '')),
                'logos' => collect($trusted['logos'] ?? [])
                    ->map(fn ($item) => [
                        'label' => trim((string) ($item['label'] ?? '')),
                        'media_id' => filled($item['media_id'] ?? null) ? (int) $item['media_id'] : null,
                    ])
                    ->filter(fn (array $item): bool => filled($item['label']) || filled($item['media_id']))
                    ->values()
                    ->all(),
            ],
            'why_tracking' => [
                'badge' => trim((string) ($whyTracking['badge'] ?? '')),
                'title' => trim((string) ($whyTracking['title'] ?? '')),
                'description' => trim((string) ($whyTracking['description'] ?? '')),
                'cta_label' => trim((string) ($whyTracking['cta_label'] ?? '')),
                'cta_url' => trim((string) ($whyTracking['cta_url'] ?? '')),
                'items' => $this->normalizeCardItems($whyTracking['items'] ?? []),
            ],
            'services_intro' => [
                'badge' => trim((string) ($servicesIntro['badge'] ?? '')),
                'title' => trim((string) ($servicesIntro['title'] ?? '')),
                'description' => trim((string) ($servicesIntro['description'] ?? '')),
            ],
            'pricing' => [
                'badge' => trim((string) ($pricing['badge'] ?? '')),
                'title' => trim((string) ($pricing['title'] ?? '')),
                'description' => trim((string) ($pricing['description'] ?? '')),
                'audit_title' => trim((string) ($pricing['audit_title'] ?? '')),
                'audit_description' => trim((string) ($pricing['audit_description'] ?? '')),
                'audit_label' => trim((string) ($pricing['audit_label'] ?? '')),
                'packages' => collect($pricing['packages'] ?? [])
                    ->map(fn ($item) => [
                        'badge' => trim((string) ($item['badge'] ?? '')),
                        'featured' => (bool) ($item['featured'] ?? false),
                        'name' => trim((string) ($item['name'] ?? '')),
                        'price' => trim((string) ($item['price'] ?? '')),
                        'timeline' => trim((string) ($item['timeline'] ?? '')),
                        'summary' => trim((string) ($item['summary'] ?? '')),
                        'items' => $this->normalizeTextItems($item['items'] ?? []),
                    ])
                    ->filter(fn (array $item): bool => filled($item['badge']) || filled($item['name']) || filled($item['price']) || filled($item['timeline']) || filled($item['summary']) || ! empty($item['items']))
                    ->values()
                    ->all(),
            ],
            'security' => [
                'badge' => trim((string) ($security['badge'] ?? '')),
                'title' => trim((string) ($security['title'] ?? '')),
                'description' => trim((string) ($security['description'] ?? '')),
                'cta_label' => trim((string) ($security['cta_label'] ?? '')),
                'items' => $this->normalizeCardItems($security['items'] ?? []),
            ],
            'case_studies' => [
                'badge' => trim((string) ($caseStudies['badge'] ?? '')),
                'title' => trim((string) ($caseStudies['title'] ?? '')),
                'description' => trim((string) ($caseStudies['description'] ?? '')),
                'studies' => collect($caseStudies['studies'] ?? [])
                    ->map(fn ($item) => [
                        'label' => trim((string) ($item['label'] ?? '')),
                        'title' => trim((string) ($item['title'] ?? '')),
                        'summary' => trim((string) ($item['summary'] ?? '')),
                        'result' => trim((string) ($item['result'] ?? '')),
                        'before_media_id' => filled($item['before_media_id'] ?? null) ? (int) $item['before_media_id'] : null,
                        'after_media_id' => filled($item['after_media_id'] ?? null) ? (int) $item['after_media_id'] : null,
                    ])
                    ->filter(fn (array $item): bool => filled($item['label']) || filled($item['title']) || filled($item['summary']) || filled($item['result']) || filled($item['before_media_id']) || filled($item['after_media_id']))
                    ->values()
                    ->all(),
            ],
            'contact_options' => [
                'badge' => trim((string) ($contactOptions['badge'] ?? '')),
                'title' => trim((string) ($contactOptions['title'] ?? '')),
                'description' => trim((string) ($contactOptions['description'] ?? '')),
                'headline' => trim((string) ($contactOptions['headline'] ?? '')),
            ],
            'benefits' => [
                'badge' => trim((string) ($benefits['badge'] ?? '')),
                'highlight' => trim((string) ($benefits['highlight'] ?? '')),
                'title' => trim((string) ($benefits['title'] ?? '')),
                'description' => trim((string) ($benefits['description'] ?? '')),
                'items' => $this->normalizeCardItems($benefits['items'] ?? []),
            ],
            'cta' => [
                'title' => trim((string) ($cta['title'] ?? '')),
                'description' => trim((string) ($cta['description'] ?? '')),
                'button_label' => trim((string) ($cta['button_label'] ?? '')),
                'button_url' => trim((string) ($cta['button_url'] ?? '')),
            ],
        ];
    }

    protected function normalizeAboutSections(array $about): array
    {
        $hero = $about['hero'] ?? [];
        $intro = $about['intro'] ?? [];
        $mission = $about['mission'] ?? [];
        $expertise = $about['expertise'] ?? [];
        $whyChoose = $about['why_choose'] ?? [];
        $cta = $about['cta'] ?? [];

        return [
            'hero' => [
                'eyebrow' => trim((string) ($hero['eyebrow'] ?? '')),
                'title' => trim((string) ($hero['title'] ?? '')),
                'description' => trim((string) ($hero['description'] ?? '')),
            ],
            'intro' => [
                'title' => trim((string) ($intro['title'] ?? '')),
                'content' => trim((string) ($intro['content'] ?? '')),
            ],
            'mission' => [
                'title' => trim((string) ($mission['title'] ?? '')),
                'content' => trim((string) ($mission['content'] ?? '')),
            ],
            'expertise' => [
                'title' => trim((string) ($expertise['title'] ?? '')),
                'items' => $this->normalizeTextItems($expertise['items'] ?? []),
            ],
            'why_choose' => [
                'title' => trim((string) ($whyChoose['title'] ?? '')),
                'items' => $this->normalizeTextItems($whyChoose['items'] ?? []),
            ],
            'cta' => [
                'title' => trim((string) ($cta['title'] ?? '')),
                'button_label' => trim((string) ($cta['button_label'] ?? '')),
                'button_url' => trim((string) ($cta['button_url'] ?? '')),
            ],
        ];
    }

    protected function normalizeBlogSections(array $blog): array
    {
        $hero = $blog['hero'] ?? [];
        $featured = $blog['featured'] ?? [];
        $postsIntro = $blog['posts_intro'] ?? [];
        $posts = $blog['posts'] ?? [];
        $cta = $blog['cta'] ?? [];

        return [
            'hero' => [
                'eyebrow' => trim((string) ($hero['eyebrow'] ?? '')),
                'title' => trim((string) ($hero['title'] ?? '')),
                'description' => trim((string) ($hero['description'] ?? '')),
            ],
            'featured' => [
                'badge' => trim((string) ($featured['badge'] ?? '')),
                'title' => trim((string) ($featured['title'] ?? '')),
                'excerpt' => trim((string) ($featured['excerpt'] ?? '')),
                'reading_time' => trim((string) ($featured['reading_time'] ?? '')),
                'slug' => trim((string) ($featured['slug'] ?? $featured['url'] ?? '')),
                'media_id' => filled($featured['media_id'] ?? null) ? (int) $featured['media_id'] : null,
            ],
            'posts_intro' => [
                'badge' => trim((string) ($postsIntro['badge'] ?? '')),
                'title' => trim((string) ($postsIntro['title'] ?? '')),
                'description' => trim((string) ($postsIntro['description'] ?? '')),
            ],
            'posts' => collect($posts)
                ->map(fn ($item) => [
                    'badge' => trim((string) ($item['badge'] ?? '')),
                    'title' => trim((string) ($item['title'] ?? '')),
                    'excerpt' => trim((string) ($item['excerpt'] ?? '')),
                    'reading_time' => trim((string) ($item['reading_time'] ?? '')),
                    'slug' => trim((string) ($item['slug'] ?? $item['url'] ?? '')),
                ])
                ->filter(fn (array $item): bool => filled($item['badge']) || filled($item['title']) || filled($item['excerpt']) || filled($item['reading_time']) || filled($item['slug']))
                ->values()
                ->all(),
            'cta' => [
                'title' => trim((string) ($cta['title'] ?? '')),
                'description' => trim((string) ($cta['description'] ?? '')),
                'button_label' => trim((string) ($cta['button_label'] ?? '')),
                'button_url' => trim((string) ($cta['button_url'] ?? '')),
            ],
        ];
    }

    protected function normalizeCardItems(array $items): array
    {
        return collect($items)
            ->map(fn ($item) => [
                'title' => trim((string) ($item['title'] ?? '')),
                'description' => trim((string) ($item['description'] ?? '')),
                'media_id' => filled($item['media_id'] ?? null) ? (int) $item['media_id'] : null,
            ])
            ->filter(fn (array $item): bool => filled($item['title']) || filled($item['description']) || filled($item['media_id']))
            ->values()
            ->all();
    }

    protected function normalizeTextItems(array $items): array
    {
        return collect($items)
            ->map(fn ($value) => trim((string) ($value['value'] ?? $value)))
            ->filter()
            ->values()
            ->all();
    }
}
