import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:url_launcher/url_launcher.dart';
import '../controllers/referral_controller.dart';
import '../../../core/utils/app_snackbar.dart';

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

  @override
  Widget build(BuildContext context) {
    final controller = Get.put(ReferralController());
    final isDark = Theme.of(context).brightness == Brightness.dark;

    return Scaffold(
      backgroundColor: isDark ? const Color(0xFF121212) : const Color(0xFFF5F7FA),
      appBar: AppBar(
        title: const Text('ادعُ واكسب', style: TextStyle(fontWeight: FontWeight.bold)),
        centerTitle: true,
        backgroundColor: const Color(0xFF0F4C81),
        foregroundColor: Colors.white,
      ),
      body: Obx(() {
        if (controller.isLoading.value) {
          return const Center(child: CircularProgressIndicator(color: Color(0xFF0F4C81)));
        }

        return SingleChildScrollView(
          padding: const EdgeInsets.all(16),
          child: Column(
            children: [
              _buildHeroBanner(controller, isDark),
              const SizedBox(height: 20),
              _buildStatsRow(controller.stats, isDark),
              const SizedBox(height: 20),
              _buildRewardsCard(controller.rewardRules, isDark),
              const SizedBox(height: 20),
              _buildHowItWorks(isDark),
              const SizedBox(height: 20),
              if (controller.recent.isNotEmpty) ...[
                _buildRecentReferrals(controller.recent, isDark),
              ],
              const SizedBox(height: 40),
            ],
          ),
        );
      }),
    );
  }

  Widget _buildHeroBanner(ReferralController controller, bool isDark) {
    return Container(
      padding: const EdgeInsets.all(24),
      decoration: BoxDecoration(
        gradient: const LinearGradient(
          colors: [Color(0xFF0F4C81), Color(0xFF1A6BB5), Color(0xFF2980B9)],
          begin: Alignment.topLeft, end: Alignment.bottomRight,
        ),
        borderRadius: BorderRadius.circular(20),
        boxShadow: [
          BoxShadow(color: const Color(0xFF0F4C81).withValues(alpha: 0.3), blurRadius: 15, offset: const Offset(0, 6)),
        ],
      ),
      child: Column(
        children: [
          const Icon(Icons.card_giftcard, size: 48, color: Color(0xFFD4AF37)),
          const SizedBox(height: 12),
          const Text(
            'ادعُ صديقك واحصل على\nشهر مجاني!',
            textAlign: TextAlign.center,
            style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold, color: Colors.white, height: 1.4),
          ),
          const SizedBox(height: 16),

          // Code display
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 14),
            decoration: BoxDecoration(
              color: Colors.white.withValues(alpha: 0.15),
              borderRadius: BorderRadius.circular(14),
              border: Border.all(color: Colors.white.withValues(alpha: 0.2)),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Expanded(
                  child: Text(
                    controller.code,
                    textAlign: TextAlign.center,
                    style: const TextStyle(fontSize: 26, fontWeight: FontWeight.w900, color: Colors.white, letterSpacing: 4, fontFamily: 'monospace'),
                  ),
                ),
              ],
            ),
          ),
          const SizedBox(height: 16),

          // WhatsApp Share Button
          SizedBox(
            width: double.infinity,
            child: ElevatedButton.icon(
              onPressed: () => _shareViaWhatsApp(controller.code, controller.link),
              icon: const Icon(Icons.chat, size: 20),
              label: const Text('أرسل عبر واتساب', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 15)),
              style: ElevatedButton.styleFrom(
                backgroundColor: const Color(0xFF25D366),
                foregroundColor: Colors.white,
                padding: const EdgeInsets.symmetric(vertical: 14),
                shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
                elevation: 4,
              ),
            ),
          ),
          const SizedBox(height: 10),

          // Copy Code + Copy Link Row
          Row(
            children: [
              Expanded(
                child: ElevatedButton.icon(
                  onPressed: () {
                    Clipboard.setData(ClipboardData(text: controller.code));
                    AppSnackbar.showSuccess('تم النسخ', 'تم نسخ رمز الإحالة: ${controller.code}');
                  },
                  icon: const Icon(Icons.copy, size: 16),
                  label: const Text('نسخ الرمز', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 13)),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.white.withValues(alpha: 0.2),
                    foregroundColor: Colors.white,
                    padding: const EdgeInsets.symmetric(vertical: 12),
                    shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
                    elevation: 0,
                  ),
                ),
              ),
              const SizedBox(width: 10),
              Expanded(
                child: ElevatedButton.icon(
                  onPressed: () {
                    Clipboard.setData(ClipboardData(text: controller.link));
                    AppSnackbar.showSuccess('تم النسخ', 'تم نسخ رابط الدعوة');
                  },
                  icon: const Icon(Icons.link, size: 16),
                  label: const Text('نسخ الرابط', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 13)),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: const Color(0xFFD4AF37),
                    foregroundColor: Colors.white,
                    padding: const EdgeInsets.symmetric(vertical: 12),
                    shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
                    elevation: 0,
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  void _shareViaWhatsApp(String code, String link) async {
    final rawMessage =
      'مرحباً 👋\n\n'
      'أدعوك لتجربة تطبيق *مُصادَق* — أذكى نظام فوترة إلكتروني في الأردن 🇯🇴\n\n'
      '✅ استخراج الفواتير بالذكاء الاصطناعي\n'
      '✅ ربط مباشر مع جوفوترة\n'
      '✅ تقارير ضريبية جاهزة\n\n'
      '🎁 استخدم رمز الدعوة: *$code*\n'
      'واحصل على شهر مجاني!\n\n'
      '🔗 $link';

    final encodedMessage = Uri.encodeComponent(rawMessage);

    // Try multiple approaches for WhatsApp
    final urls = [
      Uri.parse('whatsapp://send?text=$encodedMessage'),
      Uri.parse('https://wa.me/?text=$encodedMessage'),
    ];

    for (final url in urls) {
      try {
        final launched = await launchUrl(url, mode: LaunchMode.externalApplication);
        if (launched) return; // Success!
      } catch (_) {
        continue; // Try next URL
      }
    }

    // All failed — copy to clipboard
    Clipboard.setData(ClipboardData(text: rawMessage));
    AppSnackbar.showSuccess('تم نسخ الرسالة', 'ألصقها في واتساب أو أي تطبيق مراسلة');
  }

  Widget _buildStatsRow(Map<String, dynamic> stats, bool isDark) {
    return Row(
      children: [
        Expanded(child: _statCard('الدعوات', '${stats['total'] ?? 0}', Icons.people_alt, const Color(0xFF3B82F6), isDark)),
        const SizedBox(width: 10),
        Expanded(child: _statCard('مسجّلين', '${stats['registered'] ?? 0}', Icons.person_add, const Color(0xFF10B981), isDark)),
        const SizedBox(width: 10),
        Expanded(child: _statCard('مشتركين', '${stats['subscribed'] ?? 0}', Icons.workspace_premium, const Color(0xFFD4AF37), isDark)),
      ],
    );
  }

  Widget _statCard(String label, String value, IconData icon, Color color, bool isDark) {
    return Container(
      padding: const EdgeInsets.all(14),
      decoration: BoxDecoration(
        color: isDark ? const Color(0xFF1E1E2E) : Colors.white,
        borderRadius: BorderRadius.circular(14),
        border: Border.all(color: isDark ? Colors.white10 : Colors.grey.shade200),
      ),
      child: Column(
        children: [
          Icon(icon, size: 22, color: color),
          const SizedBox(height: 8),
          Text(value, style: TextStyle(fontSize: 22, fontWeight: FontWeight.w900, color: isDark ? Colors.white : Colors.black87, fontFamily: 'monospace')),
          const SizedBox(height: 4),
          Text(label, style: TextStyle(fontSize: 11, color: isDark ? Colors.white38 : Colors.grey)),
        ],
      ),
    );
  }

  Widget _buildRewardsCard(Map<String, dynamic> rules, bool isDark) {
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: isDark ? const Color(0xFF1E1E2E) : Colors.white,
        borderRadius: BorderRadius.circular(16),
        border: Border.all(color: const Color(0xFFD4AF37).withValues(alpha: 0.3)),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Row(
            children: [
              Icon(Icons.emoji_events, color: Color(0xFFD4AF37), size: 22),
              SizedBox(width: 8),
              Text('المكافآت', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
            ],
          ),
          const SizedBox(height: 14),
          _rewardRow('عند تسجيل صديقك', rules['per_registration'] ?? '', Icons.person_add, const Color(0xFF10B981), isDark),
          const SizedBox(height: 10),
          _rewardRow('عند اشتراكه', rules['per_subscription'] ?? '', Icons.workspace_premium, const Color(0xFFD4AF37), isDark),
        ],
      ),
    );
  }

  Widget _rewardRow(String trigger, String reward, IconData icon, Color color, bool isDark) {
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: color.withValues(alpha: 0.06),
        borderRadius: BorderRadius.circular(10),
      ),
      child: Row(
        children: [
          Icon(icon, size: 20, color: color),
          const SizedBox(width: 10),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(trigger, style: TextStyle(fontSize: 13, fontWeight: FontWeight.w600, color: isDark ? Colors.white70 : Colors.black87)),
                Text(reward, style: TextStyle(fontSize: 12, color: color, fontWeight: FontWeight.bold)),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildHowItWorks(bool isDark) {
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: isDark ? const Color(0xFF1E1E2E) : Colors.white,
        borderRadius: BorderRadius.circular(16),
        border: Border.all(color: isDark ? Colors.white10 : Colors.grey.shade200),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text('كيف يعمل؟', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold, color: isDark ? Colors.white : Colors.black87)),
          const SizedBox(height: 14),
          _stepItem('1', 'أرسل الرمز لصديقك عبر واتساب', Icons.chat, const Color(0xFF25D366), isDark),
          const SizedBox(height: 10),
          _stepItem('2', 'يسجّل في مُصادَق بالرمز', Icons.person_add, const Color(0xFF6366F1), isDark),
          const SizedBox(height: 10),
          _stepItem('3', 'كلاكما يحصل على المكافأة!', Icons.celebration, const Color(0xFFD4AF37), isDark),
        ],
      ),
    );
  }

  Widget _stepItem(String num, String text, IconData icon, Color color, bool isDark) {
    return Row(
      children: [
        Container(
          width: 32, height: 32,
          decoration: BoxDecoration(
            color: color.withValues(alpha: 0.12),
            borderRadius: BorderRadius.circular(8),
          ),
          child: Center(child: Text(num, style: TextStyle(fontWeight: FontWeight.w900, color: color, fontSize: 14))),
        ),
        const SizedBox(width: 12),
        Icon(icon, size: 18, color: color),
        const SizedBox(width: 8),
        Expanded(child: Text(text, style: TextStyle(fontSize: 13, color: isDark ? Colors.white70 : Colors.black87))),
      ],
    );
  }

  Widget _buildRecentReferrals(List recent, bool isDark) {
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: isDark ? const Color(0xFF1E1E2E) : Colors.white,
        borderRadius: BorderRadius.circular(16),
        border: Border.all(color: isDark ? Colors.white10 : Colors.grey.shade200),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text('آخر الإحالات', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold, color: isDark ? Colors.white : Colors.black87)),
          const SizedBox(height: 12),
          ...recent.map((r) {
            final status = r['status'] ?? 'clicked';
            final statusColor = status == 'subscribed' ? const Color(0xFFD4AF37) : status == 'registered' ? const Color(0xFF10B981) : Colors.grey;
            final statusLabel = status == 'subscribed' ? 'مشترك' : status == 'registered' ? 'مسجّل' : 'ضغط الرابط';

            return Padding(
              padding: const EdgeInsets.only(bottom: 8),
              child: Row(
                children: [
                  CircleAvatar(radius: 16, backgroundColor: statusColor.withValues(alpha: 0.1), child: Icon(Icons.person, size: 16, color: statusColor)),
                  const SizedBox(width: 10),
                  Expanded(child: Text(r['referred_name'] ?? 'مستخدم', style: TextStyle(fontSize: 14, color: isDark ? Colors.white : Colors.black87))),
                  Container(
                    padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
                    decoration: BoxDecoration(color: statusColor.withValues(alpha: 0.1), borderRadius: BorderRadius.circular(6)),
                    child: Text(statusLabel, style: TextStyle(fontSize: 11, color: statusColor, fontWeight: FontWeight.w600)),
                  ),
                ],
              ),
            );
          }),
        ],
      ),
    );
  }
}
