<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\DynamicPage;
use App\Models\Setting;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class DynamicPageController extends Controller
{
    /**
     * Reserved page slugs (static pages).
     */
    protected array $staticPages = [
        'about' => 'Quiénes Somos',
        'terms' => 'Términos y Condiciones',
        'privacy' => 'Política de Privacidad',
        'cookies' => 'Política de Cookies',
        'refund' => 'Política de Reembolso',
        'faq' => 'Preguntas Frecuentes',
    ];

    /**
     * Display a listing of all pages (static + dynamic).
     */
    public function index(): Response
    {
        // Get static pages
        $staticPages = [];
        foreach ($this->staticPages as $slug => $name) {
            $staticPages[] = [
                'id' => 'static_' . $slug,
                'title' => $name,
                'slug' => $slug,
                'content' => Setting::get("page_{$slug}", ''),
                'is_static' => true,
                'is_active' => true,
                'show_in_header' => false,
                'show_in_footer' => true,
                'updated_at' => Setting::where('key', "page_{$slug}")->value('updated_at'),
            ];
        }

        // Get dynamic pages
        $dynamicPages = DynamicPage::orderBy('sort_order')
            ->get()
            ->map(function ($page) {
                return [
                    'id' => $page->id,
                    'title' => $page->title,
                    'slug' => $page->slug,
                    'content' => $page->content,
                    'is_static' => false,
                    'is_active' => $page->is_active,
                    'show_in_header' => $page->show_in_header,
                    'show_in_footer' => $page->show_in_footer,
                    'sort_order' => $page->sort_order,
                    'updated_at' => $page->updated_at?->format('Y-m-d H:i'),
                ];
            })
            ->toArray();

        return Inertia::render('Admin/Pages/Index', [
            'staticPages' => $staticPages,
            'dynamicPages' => $dynamicPages,
        ]);
    }

    /**
     * Show form to create a new dynamic page.
     */
    public function create(): Response
    {
        return Inertia::render('Admin/Pages/Create');
    }

    /**
     * Store a new dynamic page.
     */
    public function store(Request $request): RedirectResponse
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'slug' => 'nullable|string|max:255|unique:dynamic_pages,slug',
            'content' => 'required|string',
            'meta_title' => 'nullable|string|max:255',
            'meta_description' => 'nullable|string|max:500',
            'show_in_header' => 'sometimes|boolean',
            'show_in_footer' => 'sometimes|boolean',
            'is_active' => 'sometimes|boolean',
        ], [
            'title.required' => 'El título es obligatorio.',
            'content.required' => 'El contenido es obligatorio.',
            'slug.unique' => 'Este slug ya está en uso.',
        ]);

        // Check if slug is reserved
        $slug = $validated['slug'] ?? DynamicPage::generateSlug($validated['title']);
        if (isset($this->staticPages[$slug])) {
            return back()->withErrors(['slug' => 'Este slug está reservado para páginas del sistema.']);
        }

        DynamicPage::create([
            'title' => $validated['title'],
            'slug' => $slug,
            'content' => $validated['content'],
            'meta_title' => $validated['meta_title'] ?? null,
            'meta_description' => $validated['meta_description'] ?? null,
            'show_in_header' => (bool) ($request->input('show_in_header', false)),
            'show_in_footer' => (bool) ($request->input('show_in_footer', true)),
            'is_active' => (bool) ($request->input('is_active', true)),
            'sort_order' => DynamicPage::max('sort_order') + 1,
            'created_by' => $request->user()->id,
        ]);

        return redirect()
            ->route('admin.pages.index')
            ->with('success', 'Página creada correctamente.');
    }

    /**
     * Show form to edit a static page.
     */
    public function editStatic(string $slug): Response
    {
        if (!isset($this->staticPages[$slug])) {
            abort(404);
        }

        return Inertia::render('Admin/Pages/EditStatic', [
            'slug' => $slug,
            'title' => $this->staticPages[$slug],
            'content' => Setting::get("page_{$slug}", $this->getDefaultContent($slug)),
        ]);
    }

    /**
     * Update a static page.
     */
    public function updateStatic(Request $request, string $slug): RedirectResponse
    {
        if (!isset($this->staticPages[$slug])) {
            abort(404);
        }

        $validated = $request->validate([
            'content' => 'required|string|max:100000',
        ], [
            'content.required' => 'El contenido es obligatorio.',
        ]);

        Setting::set("page_{$slug}", $validated['content'], 'pages');

        return back()->with('success', 'Página actualizada correctamente.');
    }

    /**
     * Show form to edit a dynamic page.
     */
    public function edit(DynamicPage $page): Response
    {
        return Inertia::render('Admin/Pages/Edit', [
            'page' => [
                'id' => $page->id,
                'title' => $page->title,
                'slug' => $page->slug,
                'content' => $page->content,
                'meta_title' => $page->meta_title,
                'meta_description' => $page->meta_description,
                'show_in_header' => $page->show_in_header,
                'show_in_footer' => $page->show_in_footer,
                'is_active' => $page->is_active,
            ],
        ]);
    }

    /**
     * Update a dynamic page.
     */
    public function update(Request $request, DynamicPage $page): RedirectResponse
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'slug' => 'nullable|string|max:255|unique:dynamic_pages,slug,' . $page->id,
            'content' => 'required|string',
            'meta_title' => 'nullable|string|max:255',
            'meta_description' => 'nullable|string|max:500',
            'show_in_header' => 'sometimes|boolean',
            'show_in_footer' => 'sometimes|boolean',
            'is_active' => 'sometimes|boolean',
        ], [
            'title.required' => 'El título es obligatorio.',
            'content.required' => 'El contenido es obligatorio.',
            'slug.unique' => 'Este slug ya está en uso.',
        ]);

        $slug = $validated['slug'] ?? DynamicPage::generateSlug($validated['title'], $page->id);
        if (isset($this->staticPages[$slug])) {
            return back()->withErrors(['slug' => 'Este slug está reservado para páginas del sistema.']);
        }

        $page->update([
            'title' => $validated['title'],
            'slug' => $slug,
            'content' => $validated['content'],
            'meta_title' => $validated['meta_title'] ?? null,
            'meta_description' => $validated['meta_description'] ?? null,
            'show_in_header' => (bool) ($request->input('show_in_header', false)),
            'show_in_footer' => (bool) ($request->input('show_in_footer', false)),
            'is_active' => (bool) ($request->input('is_active', false)),
        ]);

        return back()->with('success', 'Página actualizada correctamente.');
    }

    /**
     * Toggle page visibility.
     */
    public function toggle(DynamicPage $page): RedirectResponse
    {
        $page->update(['is_active' => !$page->is_active]);

        return back()->with('success', $page->is_active ? 'Página activada.' : 'Página desactivada.');
    }

    /**
     * Toggle specific visibility field (show_in_header or show_in_footer).
     */
    public function toggleVisibility(Request $request, DynamicPage $page): RedirectResponse
    {
        $field = $request->input('field');
        
        if (!in_array($field, ['show_in_header', 'show_in_footer'])) {
            return back()->with('error', 'Campo no válido.');
        }

        $page->update([$field => !$page->{$field}]);

        $fieldName = $field === 'show_in_header' ? 'Header' : 'Footer';
        $status = $page->{$field} ? 'visible' : 'oculta';

        return back()->with('success', "Página {$status} en {$fieldName}.");
    }

    /**
     * Delete a dynamic page.
     */
    public function destroy(DynamicPage $page): RedirectResponse
    {
        $page->delete();

        return redirect()
            ->route('admin.pages.index')
            ->with('success', 'Página eliminada correctamente.');
    }

    /**
     * Reorder pages.
     */
    public function reorder(Request $request): RedirectResponse
    {
        $request->validate([
            'items' => 'required|array',
            'items.*.id' => 'required|exists:dynamic_pages,id',
            'items.*.sort_order' => 'required|integer',
        ]);

        foreach ($request->items as $item) {
            DynamicPage::where('id', $item['id'])
                ->update(['sort_order' => $item['sort_order']]);
        }

        return back()->with('success', 'Orden actualizado.');
    }

    /**
     * Get default content for static pages.
     */
    private function getDefaultContent(string $slug): string
    {
        $defaults = [
            'about' => '<h1>Sobre CoachPro</h1><p>CoachPro es la plataforma líder para entrenadores personales.</p>',
            'terms' => '<h1>Términos y Condiciones</h1><p>Al usar CoachPro aceptas estos términos...</p>',
            'privacy' => '<h1>Política de Privacidad</h1><p>Tu privacidad es importante para nosotros...</p>',
            'cookies' => '<h1>Política de Cookies</h1><p>Este sitio utiliza cookies para mejorar tu experiencia...</p>',
            'refund' => '<h1>Política de Reembolso</h1><p>Puedes solicitar reembolso dentro de los primeros 7 días...</p>',
            'faq' => '<h1>Preguntas Frecuentes</h1><p><strong>¿Cómo empiezo?</strong></p><p>Regístrate y comienza tu prueba gratis.</p>',
        ];

        return $defaults[$slug] ?? '<p>Contenido de la página...</p>';
    }
}
