<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\LandingFeature;
use App\Models\LandingSetting;
use App\Models\LandingStat;
use App\Models\LandingTestimonial;
use App\Models\Plan;
use App\Models\Post;
use App\Models\SocialLink;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Inertia\Inertia;
use Inertia\Response;

class LandingController extends Controller
{
    /**
     * Display the landing page editor.
     */
    public function index(): Response
    {
        return Inertia::render('Admin/Landing/Index', [
            'settings' => $this->getAllSettings(),
            'features' => LandingFeature::orderBy('sort_order')->get(),
            'testimonials' => LandingTestimonial::with('coach', 'reviewer')
                ->orderBy('sort_order')
                ->get()
                ->map(function ($testimonial) {
                    return [
                        'id' => $testimonial->id,
                        'name' => $testimonial->name,
                        'role' => $testimonial->role,
                        'content' => $testimonial->content,
                        'avatar' => $testimonial->avatar,
                        'rating' => $testimonial->rating,
                        'sort_order' => $testimonial->sort_order,
                        'is_active' => $testimonial->is_active,
                        'status' => $testimonial->status,
                        'source' => $testimonial->source,
                        'rejection_reason' => $testimonial->rejection_reason,
                        'submitted_at' => $testimonial->submitted_at?->format('d/m/Y H:i'),
                        'reviewed_at' => $testimonial->reviewed_at?->format('d/m/Y H:i'),
                        'coach' => $testimonial->coach ? [
                            'id' => $testimonial->coach->id,
                            'name' => $testimonial->coach->name,
                            'email' => $testimonial->coach->email,
                            'avatar' => $testimonial->coach->avatar_url,
                        ] : null,
                        'reviewer' => $testimonial->reviewer ? [
                            'name' => $testimonial->reviewer->name,
                        ] : null,
                    ];
                }),
            'pendingTestimonialsCount' => LandingTestimonial::pending()->fromCoaches()->count(),
            'stats' => LandingStat::orderBy('sort_order')->get(),
            'socialLinks' => SocialLink::orderBy('sort_order')->get(),
            'plans' => Plan::where('is_active', true)->orderBy('price')->get(),
            'availableIcons' => $this->getAvailableIcons(),
            'platformOptions' => array_keys(SocialLink::$platformIcons),
        ]);
    }

    /**
     * Get all landing settings organized by section.
     */
    private function getAllSettings(): array
    {
        $defaults = $this->getDefaultSettings();
        $saved = LandingSetting::all()->groupBy('section')->map(function ($items) {
            return $items->pluck('value', 'key')->map(function ($value) {
                $decoded = json_decode($value, true);
                return json_last_error() === JSON_ERROR_NONE ? $decoded : $value;
            })->toArray();
        })->toArray();

        return array_replace_recursive($defaults, $saved);
    }

    /**
     * Get default settings.
     */
    private function getDefaultSettings(): array
    {
        return [
            'hero' => [
                'title' => 'Transforma tu Negocio de Coaching',
                'subtitle' => 'La plataforma todo-en-uno para coaches y entrenadores de fitness. Gestiona clientes, crea planes personalizados y haz crecer tu negocio.',
                'cta_text' => 'Comenzar Ahora',
                'cta_link' => '/register',
                'secondary_cta_text' => 'Ver Planes',
                'secondary_cta_link' => '#planes',
                'background_image' => null,
                'show_stats' => true,
            ],
            'benefits' => [
                'title' => '¿Por qué elegir CoachPro?',
                'subtitle' => 'Todo lo que necesitas para gestionar tu negocio de coaching en un solo lugar',
            ],
            'plans_section' => [
                'title' => 'Planes que se adaptan a ti',
                'subtitle' => 'Elige el plan perfecto para tu negocio. Sin contratos, cancela cuando quieras.',
                'show_section' => true,
            ],
            'testimonials_section' => [
                'title' => 'Lo que dicen nuestros coaches',
                'subtitle' => 'Miles de entrenadores confían en CoachPro para hacer crecer su negocio',
                'show_section' => true,
            ],
            'blog_section' => [
                'title' => 'Últimos Artículos',
                'subtitle' => 'Consejos, tendencias y recursos para coaches de fitness',
                'show_section' => true,
                'posts_count' => 3,
            ],
            'cta_section' => [
                'title' => '¿Listo para transformar tu negocio?',
                'subtitle' => 'Únete a miles de coaches que ya están usando CoachPro',
                'cta_text' => 'Empieza Gratis',
                'cta_link' => '/register',
                'show_section' => true,
            ],
            'footer' => [
                'description' => 'La plataforma líder para coaches y entrenadores de fitness. Gestiona tu negocio, clientes y contenido desde un solo lugar.',
                'copyright' => '© ' . date('Y') . ' CoachPro. Todos los derechos reservados.',
                'show_social_links' => true,
            ],
            'colors' => [
                'primary' => '#3B82F6',
                'secondary' => '#8B5CF6',
                'accent' => '#10B981',
                'dark' => '#1F2937',
            ],
            'general' => [
                'site_name' => 'CoachPro',
                'logo' => null,
                'favicon' => null,
                'meta_title' => 'CoachPro - Plataforma para Coaches de Fitness',
                'meta_description' => 'La plataforma todo-en-uno para coaches y entrenadores de fitness. Gestiona clientes, crea planes personalizados y haz crecer tu negocio.',
            ],
        ];
    }

    /**
     * Update landing settings.
     */
    public function updateSettings(Request $request)
    {
        $request->validate([
            'section' => 'required|string',
            'settings' => 'required|array',
        ]);

        $section = $request->section;
        $settings = $request->settings;

        foreach ($settings as $key => $value) {
            LandingSetting::setValue($section, $key, $value);
        }

        LandingSetting::clearCache();

        return back()->with('success', 'Configuración actualizada correctamente.');
    }

    /**
     * Upload an image for the landing page.
     */
    public function uploadImage(Request $request)
    {
        $request->validate([
            'image' => 'required|image|mimes:jpeg,png,jpg,gif,webp|max:5120',
            'type' => 'required|string|in:hero,logo,favicon,testimonial,feature',
        ]);

        $path = $request->file('image')->store('landing/' . $request->type, 'public');

        return response()->json([
            'url' => Storage::disk('public')->url($path),
            'path' => $path,
        ]);
    }

    // =====================
    // FEATURES CRUD
    // =====================

    public function storeFeature(Request $request)
    {
        $validated = $request->validate([
            'icon' => 'required|string|max:50',
            'title' => 'required|string|max:255',
            'description' => 'required|string|max:1000',
            'sort_order' => 'nullable|integer',
            'is_active' => 'boolean',
        ]);

        $validated['sort_order'] = $validated['sort_order'] ?? LandingFeature::max('sort_order') + 1;

        LandingFeature::create($validated);

        return back()->with('success', 'Característica creada correctamente.');
    }

    public function updateFeature(Request $request, LandingFeature $feature)
    {
        $validated = $request->validate([
            'icon' => 'required|string|max:50',
            'title' => 'required|string|max:255',
            'description' => 'required|string|max:1000',
            'sort_order' => 'nullable|integer',
            'is_active' => 'boolean',
        ]);

        $feature->update($validated);

        return back()->with('success', 'Característica actualizada correctamente.');
    }

    public function destroyFeature(LandingFeature $feature)
    {
        $feature->delete();
        return back()->with('success', 'Característica eliminada correctamente.');
    }

    public function reorderFeatures(Request $request)
    {
        $request->validate([
            'items' => 'required|array',
            'items.*.id' => 'required|exists:landing_features,id',
            'items.*.sort_order' => 'required|integer',
        ]);

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

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

    // =====================
    // TESTIMONIALS CRUD
    // =====================

    public function storeTestimonial(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'role' => 'nullable|string|max:255',
            'content' => 'required|string|max:1000',
            'avatar' => 'nullable|string',
            'rating' => 'integer|min:1|max:5',
            'sort_order' => 'nullable|integer',
            'is_active' => 'boolean',
        ]);

        $validated['sort_order'] = $validated['sort_order'] ?? LandingTestimonial::max('sort_order') + 1;
        $validated['rating'] = $validated['rating'] ?? 5;

        LandingTestimonial::create($validated);

        return back()->with('success', 'Testimonio creado correctamente.');
    }

    public function updateTestimonial(Request $request, LandingTestimonial $testimonial)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'role' => 'nullable|string|max:255',
            'content' => 'required|string|max:1000',
            'avatar' => 'nullable|string',
            'rating' => 'integer|min:1|max:5',
            'sort_order' => 'nullable|integer',
            'is_active' => 'boolean',
        ]);

        $testimonial->update($validated);

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

    public function destroyTestimonial(LandingTestimonial $testimonial)
    {
        $testimonial->delete();
        return back()->with('success', 'Testimonio eliminado correctamente.');
    }

    /**
     * Approve a testimonial submitted by a coach.
     */
    public function approveTestimonial(Request $request, LandingTestimonial $testimonial)
    {
        $testimonial->approve(auth()->id());

        // Notify the coach their testimonial was approved
        if ($testimonial->coach) {
            $testimonial->coach->notify(new \App\Notifications\TestimonialApproved($testimonial));
        }

        return back()->with('success', 'Testimonio aprobado y publicado correctamente.');
    }

    /**
     * Reject a testimonial submitted by a coach.
     */
    public function rejectTestimonial(Request $request, LandingTestimonial $testimonial)
    {
        $request->validate([
            'rejection_reason' => 'nullable|string|max:500',
        ]);

        $testimonial->reject(auth()->id(), $request->rejection_reason);

        // Notify the coach their testimonial was rejected
        if ($testimonial->coach) {
            $testimonial->coach->notify(new \App\Notifications\TestimonialRejected($testimonial));
        }

        return back()->with('success', 'Testimonio rechazado.');
    }

    /**
     * Get pending testimonials count for badge.
     */
    public static function getPendingTestimonialsCount(): int
    {
        return LandingTestimonial::pending()->count();
    }

    // =====================
    // STATS CRUD
    // =====================

    public function storeStat(Request $request)
    {
        $validated = $request->validate([
            'label' => 'required|string|max:255',
            'value' => 'required|string|max:50',
            'icon' => 'nullable|string|max:50',
            'sort_order' => 'nullable|integer',
            'is_active' => 'boolean',
        ]);

        $validated['sort_order'] = $validated['sort_order'] ?? LandingStat::max('sort_order') + 1;

        LandingStat::create($validated);

        return back()->with('success', 'Estadística creada correctamente.');
    }

    public function updateStat(Request $request, LandingStat $stat)
    {
        $validated = $request->validate([
            'label' => 'required|string|max:255',
            'value' => 'required|string|max:50',
            'icon' => 'nullable|string|max:50',
            'sort_order' => 'nullable|integer',
            'is_active' => 'boolean',
        ]);

        $stat->update($validated);

        return back()->with('success', 'Estadística actualizada correctamente.');
    }

    public function destroyStat(LandingStat $stat)
    {
        $stat->delete();
        return back()->with('success', 'Estadística eliminada correctamente.');
    }

    // =====================
    // SOCIAL LINKS CRUD
    // =====================

    public function storeSocialLink(Request $request)
    {
        $validated = $request->validate([
            'platform' => 'required|string|in:' . implode(',', array_keys(SocialLink::$platformIcons)),
            'url' => 'required|url|max:500',
            'sort_order' => 'nullable|integer',
            'is_active' => 'boolean',
        ]);

        $validated['sort_order'] = $validated['sort_order'] ?? SocialLink::max('sort_order') + 1;

        SocialLink::create($validated);

        return back()->with('success', 'Red social agregada correctamente.');
    }

    public function updateSocialLink(Request $request, SocialLink $socialLink)
    {
        $validated = $request->validate([
            'platform' => 'required|string|in:' . implode(',', array_keys(SocialLink::$platformIcons)),
            'url' => 'required|url|max:500',
            'sort_order' => 'nullable|integer',
            'is_active' => 'boolean',
        ]);

        $socialLink->update($validated);

        return back()->with('success', 'Red social actualizada correctamente.');
    }

    public function destroySocialLink(SocialLink $socialLink)
    {
        $socialLink->delete();
        return back()->with('success', 'Red social eliminada correctamente.');
    }

    /**
     * Get available icons list.
     */
    private function getAvailableIcons(): array
    {
        return [
            'users' => 'Usuarios',
            'chart-bar' => 'Gráfico',
            'calendar' => 'Calendario',
            'clipboard' => 'Portapapeles',
            'heart' => 'Corazón',
            'lightning-bolt' => 'Rayo',
            'star' => 'Estrella',
            'shield-check' => 'Escudo',
            'device-mobile' => 'Móvil',
            'globe' => 'Globo',
            'currency-dollar' => 'Dinero',
            'clock' => 'Reloj',
            'chat' => 'Chat',
            'document' => 'Documento',
            'photograph' => 'Foto',
            'video-camera' => 'Video',
            'music-note' => 'Música',
            'fire' => 'Fuego',
            'sparkles' => 'Brillos',
            'trophy' => 'Trofeo',
            'academic-cap' => 'Graduación',
            'beaker' => 'Ciencia',
            'briefcase' => 'Maletín',
            'cake' => 'Pastel',
            'chip' => 'Chip',
            'cube' => 'Cubo',
            'database' => 'Base de datos',
            'desktop-computer' => 'Computadora',
            'emoji-happy' => 'Feliz',
            'finger-print' => 'Huella',
            'gift' => 'Regalo',
            'hand' => 'Mano',
            'home' => 'Casa',
            'key' => 'Llave',
            'light-bulb' => 'Bombilla',
            'location-marker' => 'Ubicación',
            'lock-closed' => 'Candado',
            'mail' => 'Correo',
            'map' => 'Mapa',
            'microphone' => 'Micrófono',
            'moon' => 'Luna',
            'newspaper' => 'Periódico',
            'paper-airplane' => 'Avión de papel',
            'pencil' => 'Lápiz',
            'phone' => 'Teléfono',
            'play' => 'Reproducir',
            'puzzle' => 'Puzzle',
            'qrcode' => 'QR',
            'receipt-tax' => 'Recibo',
            'refresh' => 'Actualizar',
            'save' => 'Guardar',
            'scale' => 'Balanza',
            'search' => 'Buscar',
            'server' => 'Servidor',
            'share' => 'Compartir',
            'shopping-bag' => 'Bolsa de compras',
            'shopping-cart' => 'Carrito',
            'speakerphone' => 'Megáfono',
            'sun' => 'Sol',
            'support' => 'Soporte',
            'tag' => 'Etiqueta',
            'template' => 'Plantilla',
            'terminal' => 'Terminal',
            'thumb-up' => 'Pulgar arriba',
            'ticket' => 'Boleto',
            'translate' => 'Traducir',
            'trash' => 'Papelera',
            'trending-up' => 'Tendencia',
            'truck' => 'Camión',
            'upload' => 'Subir',
            'user-group' => 'Grupo',
            'variable' => 'Variable',
            'wifi' => 'WiFi',
            'zoom-in' => 'Zoom',
        ];
    }

    /**
     * Preview the landing page.
     */
    public function preview(): Response
    {
        return Inertia::render('Landing/Preview', $this->getLandingData());
    }

    /**
     * Get all data needed for the landing page.
     */
    public static function getLandingData(): array
    {
        $settings = LandingSetting::getAllSettings();
        
        return [
            'settings' => $settings,
            'features' => LandingFeature::getActive(),
            'testimonials' => LandingTestimonial::getActive(),
            'stats' => LandingStat::getActive(),
            'socialLinks' => SocialLink::getActive()->map(function ($link) {
                return [
                    'id' => $link->id,
                    'platform' => $link->platform,
                    'url' => $link->url,
                    'icon' => $link->getIconSvg(),
                ];
            }),
            'plans' => Plan::where('is_active', true)
                ->orderBy('price')
                ->get()
                ->map(function ($plan) {
                    return [
                        'id' => $plan->id,
                        'name' => $plan->name,
                        'slug' => $plan->slug,
                        'description' => $plan->description,
                        'price' => $plan->price,
                        'duration_days' => $plan->duration_days,
                        'features' => $plan->features ?? [],
                        'is_featured' => $plan->is_featured ?? false,
                    ];
                }),
            'latestPosts' => Post::where('is_published', true)
                ->latest('published_at')
                ->take($settings['blog_section']['posts_count'] ?? 3)
                ->get()
                ->map(function ($post) {
                    return [
                        'id' => $post->id,
                        'title' => $post->title,
                        'slug' => $post->slug,
                        'excerpt' => $post->excerpt ?? Str::limit(strip_tags($post->content), 150),
                        'featured_image' => $post->featured_image,
                        'published_at' => $post->published_at,
                        'author' => $post->author?->name ?? 'Admin',
                    ];
                }),
            'legalPages' => collect([
                ['slug' => 'about', 'title' => 'Quiénes Somos'],
                ['slug' => 'terms', 'title' => 'Términos y Condiciones'],
                ['slug' => 'privacy', 'title' => 'Política de Privacidad'],
                ['slug' => 'refund', 'title' => 'Política de Reembolso'],
            ]),
        ];
    }
}
