import 'package:flutter/material.dart';
import 'package:prosapp_web_app/models/setting.dart';
import 'package:prosapp_web_app/providers/settings_provider.dart';
import 'package:prosapp_web_app/providers/theme_provider.dart';
import 'package:prosapp_web_app/services/api_service.dart';
import 'package:provider/provider.dart';
import 'package:url_launcher/url_launcher.dart';

class SupportView extends StatelessWidget {
  const SupportView({super.key});

  Future<void> _launchURL(String url) async {
    if (url.isEmpty) return;
    final uri = Uri.parse(url);
    if (await canLaunchUrl(uri)) {
      await launchUrl(uri, mode: LaunchMode.externalApplication, webOnlyWindowName: '_blank');
    }
  }

  Future<void> _goSugerencias(BuildContext context) async {
    final controller = TextEditingController();
    final api = ApiService.instance;
    bool sending = false;

    await showDialog(
      context: context,
      builder: (ctx) => StatefulBuilder(
        builder: (ctx, setState) => AlertDialog(
          title: const Text('Enviar sugerencia'),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              const Text('Cuéntanos cómo podemos mejorar ProsApp',
                  style: TextStyle(fontSize: 14)),
              const SizedBox(height: 16),
              TextField(
                controller: controller,
                maxLines: 4,
                decoration: const InputDecoration(
                  hintText: 'Escribe tu sugerencia aquí...',
                  border: OutlineInputBorder(),
                ),
              ),
            ],
          ),
          actions: [
            TextButton(
              onPressed: sending ? null : () => Navigator.pop(ctx),
              child: const Text('Cancelar'),
            ),
            FilledButton(
              onPressed: sending
                  ? null
                  : () async {
                      final msg = controller.text.trim();
                      if (msg.isEmpty) return;
                      setState(() => sending = true);
                      try {
                        await api.post('/suggestions', {'message': msg});
                        if (ctx.mounted) {
                          Navigator.pop(ctx);
                          ScaffoldMessenger.of(context).showSnackBar(
                            const SnackBar(
                              content: Text('¡Gracias por tu sugerencia!'),
                              backgroundColor: Colors.green,
                            ),
                          );
                        }
                      } catch (_) {
                        setState(() => sending = false);
                        if (ctx.mounted) {
                          ScaffoldMessenger.of(context).showSnackBar(
                            const SnackBar(
                              content: Text('Error al enviar. Intenta de nuevo.'),
                              backgroundColor: Colors.red,
                            ),
                          );
                        }
                      }
                    },
              child: sending
                  ? const SizedBox(
                      width: 16,
                      height: 16,
                      child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white),
                    )
                  : const Text('Enviar'),
            ),
          ],
        ),
      ),
    );
  }

  Future<void> _showPolicy(BuildContext context, String title, String key, bool isDark) async {
    final api = ApiService.instance;
    String? content;
    try {
      final data = await api.get('/settings/policies') as Map<String, dynamic>;
      content = data[key] as String?;
    } catch (_) {}

    if (!context.mounted) return;

    showDialog(
      context: context,
      builder: (_) => Dialog(
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
        child: Container(
          constraints: const BoxConstraints(maxWidth: 600, maxHeight: 600),
          padding: const EdgeInsets.all(24),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Expanded(
                    child: Text(title,
                        style: TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.bold,
                          color: isDark ? Colors.white : const Color(0xFF0F172A),
                        )),
                  ),
                  IconButton(
                    icon: const Icon(Icons.close),
                    onPressed: () => Navigator.pop(context),
                  ),
                ],
              ),
              const Divider(height: 24),
              Expanded(
                child: SingleChildScrollView(
                  child: Text(
                    (content != null && content.isNotEmpty)
                        ? content
                        : 'Contenido no disponible aún.',
                    style: TextStyle(
                      fontSize: 14,
                      height: 1.6,
                      color: isDark ? Colors.white70 : const Color(0xFF374151),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final isDark = context.watch<ThemeProvider>().isDark;

    return Consumer<SettingsProvider>(
      builder: (context, settingsProvider, _) {
        final settings = settingsProvider.settings ?? Setting.fromDocument({});

        final cardBg = isDark ? const Color(0xFF1E293B) : Colors.white;
        final borderColor = isDark ? const Color(0xFF334155) : const Color(0xFFE5E7EB);
        final textPrimary = isDark ? Colors.white : const Color(0xFF111827);
        final textSecondary = isDark ? const Color(0xFF94A3B8) : const Color(0xFF6B7280);

        return ListView(
          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 20),
          children: [
            Center(
              child: ConstrainedBox(
                constraints: const BoxConstraints(maxWidth: 680),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: [

                    // ── Header ──
                    Container(
                      padding: const EdgeInsets.all(24),
                      decoration: BoxDecoration(
                        gradient: const LinearGradient(
                          colors: [Color(0xFF42A4EF), Color(0xFF1565C0)],
                          begin: Alignment.topLeft,
                          end: Alignment.bottomRight,
                        ),
                        borderRadius: BorderRadius.circular(16),
                      ),
                      child: Column(
                        children: [
                          const Icon(Icons.support_agent_rounded, color: Colors.white, size: 44),
                          const SizedBox(height: 12),
                          Text(
                            settings.tituloSoporte,
                            style: const TextStyle(
                              color: Colors.white,
                              fontSize: 22,
                              fontWeight: FontWeight.bold,
                            ),
                            textAlign: TextAlign.center,
                          ),
                          if (settings.parrafoSoporte.isNotEmpty) ...[
                            const SizedBox(height: 8),
                            Text(
                              settings.parrafoSoporte,
                              style: const TextStyle(color: Colors.white70, fontSize: 13),
                              textAlign: TextAlign.center,
                            ),
                          ],
                        ],
                      ),
                    ),

                    const SizedBox(height: 16),

                    // ── Horario ──
                    Container(
                      padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 14),
                      decoration: BoxDecoration(
                        color: cardBg,
                        borderRadius: BorderRadius.circular(12),
                        border: Border.all(color: borderColor),
                      ),
                      child: Row(
                        children: [
                          Container(
                            padding: const EdgeInsets.all(10),
                            decoration: BoxDecoration(
                              color: const Color(0xFF42A4EF).withOpacity(0.1),
                              shape: BoxShape.circle,
                            ),
                            child: const Icon(Icons.schedule, color: Color(0xFF42A4EF), size: 20),
                          ),
                          const SizedBox(width: 14),
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text('Horario de atención',
                                  style: TextStyle(
                                    fontSize: 13,
                                    fontWeight: FontWeight.w600,
                                    color: textPrimary,
                                  )),
                              const SizedBox(height: 2),
                              Text(
                                '${settings.diasSoporte}  •  ${settings.horasSoporte}',
                                style: TextStyle(fontSize: 12, color: textSecondary),
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),

                    const SizedBox(height: 16),

                    // ── Contacto ──
                    Text('Contáctanos',
                        style: TextStyle(
                          fontSize: 13,
                          fontWeight: FontWeight.w600,
                          color: textSecondary,
                          letterSpacing: 0.4,
                        )),
                    const SizedBox(height: 8),

                    _ContactTile(
                      icon: Icons.chat_rounded,
                      iconColor: const Color(0xFF25D366),
                      label: 'WhatsApp',
                      subtitle: settings.numeroSoporte.isNotEmpty
                          ? (settings.numeroSoporte.startsWith('+')
                              ? settings.numeroSoporte
                              : '+${settings.numeroSoporte}')
                          : 'No configurado',
                      isDark: isDark,
                      cardBg: cardBg,
                      borderColor: borderColor,
                      onTap: settings.numeroSoporte.isNotEmpty
                          ? () => _launchURL(
                              'https://api.whatsapp.com/send?phone=${settings.numeroSoporte.replaceAll('+', '').replaceAll(' ', '')}&text=${Uri.encodeComponent('Hola, soy usuario de ProsApp')}')
                          : null,
                    ),

                    const SizedBox(height: 8),

                    _ContactTile(
                      icon: Icons.email_outlined,
                      iconColor: const Color(0xFF42A4EF),
                      label: 'Email',
                      subtitle: settings.emailSoporte.isNotEmpty
                          ? settings.emailSoporte
                          : 'No configurado',
                      isDark: isDark,
                      cardBg: cardBg,
                      borderColor: borderColor,
                      onTap: settings.emailSoporte.isNotEmpty
                          ? () => _launchURL('mailto:${settings.emailSoporte}')
                          : null,
                    ),

                    const SizedBox(height: 8),

                    _ContactTile(
                      icon: Icons.lightbulb_outline,
                      iconColor: const Color(0xFFF59E0B),
                      label: 'Sugerencias',
                      subtitle: 'Ayúdanos a mejorar ProsApp',
                      isDark: isDark,
                      cardBg: cardBg,
                      borderColor: borderColor,
                      onTap: () => _goSugerencias(context),
                    ),

                    const SizedBox(height: 20),

                    // ── Legal ──
                    Text('Legal',
                        style: TextStyle(
                          fontSize: 13,
                          fontWeight: FontWeight.w600,
                          color: textSecondary,
                          letterSpacing: 0.4,
                        )),
                    const SizedBox(height: 8),

                    _ContactTile(
                      icon: Icons.shield_outlined,
                      iconColor: const Color(0xFF8B5CF6),
                      label: 'Políticas de Privacidad',
                      subtitle: 'Cómo protegemos tus datos',
                      isDark: isDark,
                      cardBg: cardBg,
                      borderColor: borderColor,
                      onTap: () => _showPolicy(context, 'Políticas de Privacidad', 'privacy', isDark),
                    ),

                    const SizedBox(height: 8),

                    _ContactTile(
                      icon: Icons.article_outlined,
                      iconColor: const Color(0xFF10B981),
                      label: 'Términos y Condiciones',
                      subtitle: 'Condiciones de uso de la plataforma',
                      isDark: isDark,
                      cardBg: cardBg,
                      borderColor: borderColor,
                      onTap: () => _showPolicy(context, 'Términos y Condiciones', 'terms', isDark),
                    ),

                    const SizedBox(height: 24),
                  ],
                ),
              ),
            ),
          ],
        );
      },
    );
  }
}

class _ContactTile extends StatelessWidget {
  final IconData icon;
  final Color iconColor;
  final String label;
  final String subtitle;
  final bool isDark;
  final Color cardBg;
  final Color borderColor;
  final VoidCallback? onTap;

  const _ContactTile({
    required this.icon,
    required this.iconColor,
    required this.label,
    required this.subtitle,
    required this.isDark,
    required this.cardBg,
    required this.borderColor,
    this.onTap,
  });

  @override
  Widget build(BuildContext context) {
    final textPrimary = isDark ? Colors.white : const Color(0xFF111827);
    final textSecondary = isDark ? const Color(0xFF94A3B8) : const Color(0xFF6B7280);

    return Material(
      color: cardBg,
      borderRadius: BorderRadius.circular(12),
      child: InkWell(
        onTap: onTap,
        borderRadius: BorderRadius.circular(12),
        child: Container(
          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(12),
            border: Border.all(color: borderColor),
          ),
          child: Row(
            children: [
              Container(
                padding: const EdgeInsets.all(9),
                decoration: BoxDecoration(
                  color: iconColor.withOpacity(0.12),
                  shape: BoxShape.circle,
                ),
                child: Icon(icon, color: iconColor, size: 20),
              ),
              const SizedBox(width: 14),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(label,
                        style: TextStyle(
                          fontSize: 14,
                          fontWeight: FontWeight.w600,
                          color: textPrimary,
                        )),
                    const SizedBox(height: 2),
                    Text(subtitle,
                        style: TextStyle(fontSize: 12, color: textSecondary)),
                  ],
                ),
              ),
              if (onTap != null)
                Icon(Icons.chevron_right, color: textSecondary, size: 20),
            ],
          ),
        ),
      ),
    );
  }
}
