import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:mypoint_flutter_app/features/support/support_item_model.dart';
import 'package:mypoint_flutter_app/features/support/support_screen_viewmodel.dart';
import 'package:mypoint_flutter_app/shared/router_gage.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:universal_html/js_util.dart' as js_util;
import '../../shared/widgets/custom_navigation_bar.dart';
import '../faqs/faqs_screen.dart';
import '../pageDetail/model/detail_page_rule_type.dart';
import '../../core/services/web/web_helper.dart';

class SupportScreen extends StatefulWidget {
  const SupportScreen({super.key});

  @override
  State<SupportScreen> createState() => _SupportScreenState();
}

class _SupportScreenState extends State<SupportScreen> {
  final SupportViewModel controller = Get.put(SupportViewModel());

  void _handleItemClick(SupportItemType type, String value) async {
    switch (type) {
      case SupportItemType.mail:
        final Uri emailUri = Uri(scheme: 'mailto', path: value);
        if (await canLaunchUrl(emailUri)) {
          await launchUrl(emailUri);
        }
        break;
      case SupportItemType.phone:
        final phone = value.trim();
        if (phone.isEmpty) {
          debugPrint('⚠️ SupportScreen: phone number is empty');
          return;
        }
        if (kIsWeb) {
          try {
            final result = await webCallPhone(phone);
            if (!_isSdkSuccess(result)) {
              await _launchTelUrl(phone);
            }
          } catch (e) {
            debugPrint('❌ webCallPhone failed: $e');
            await _launchTelUrl(phone);
          }
        } else {
          await _launchTelUrl(phone);
        }
        return;
      case SupportItemType.facebook:
        final Uri fbUri = Uri.parse(value);
        if (await canLaunchUrl(fbUri)) {
          await launchUrl(fbUri);
        }
        break;
      case SupportItemType.question:
        Get.to(FAQScreen());
        return;
      case SupportItemType.termsOfUse:
        Get.toNamed(campaignDetailScreen, arguments: {"type": DetailPageRuleType.termsOfUse});
        return;
      case SupportItemType.privacyPolicy:
        Get.toNamed(campaignDetailScreen, arguments: {"type": DetailPageRuleType.privacyPolicy});
        return;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CustomNavigationBar(title: "Hỗ trợ"),
      body: Obx(() {
        if (controller.supportItems.isEmpty) {
          return const Center(child: CircularProgressIndicator());
        }
        return ListView.builder(
          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
          itemCount: controller.supportItems.length,
          itemBuilder: (context, index) {
            final item = controller.supportItems[index];
            return GestureDetector(
              onTap: () => _handleItemClick(item.type, item.value),
              child: Container(
                margin: const EdgeInsets.only(bottom: 10),
                padding: const EdgeInsets.all(16),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(10),
                  boxShadow: [BoxShadow(color: Colors.black12, blurRadius: 4)],
                ),
                child: Row(
                  children: [
                    Icon(_getIcon(item.type), color: Colors.black54, size: 24),
                    const SizedBox(width: 10),
                    Expanded(
                      child: Text(item.title, style: const TextStyle(fontSize: 16)),
                    ),
                    if (_hasArrow(item.type))
                      const Icon(Icons.arrow_forward_ios, size: 16, color: Colors.black54),
                  ],
                ),
              ),
            );
          },
        );
      }),
    );
  }

  IconData _getIcon(SupportItemType type) {
    switch (type) {
      case SupportItemType.mail:
        return Icons.email;
      case SupportItemType.phone:
        return Icons.phone;
      case SupportItemType.facebook:
        return Icons.facebook;
      case SupportItemType.question:
        return Icons.help_outline;
      case SupportItemType.termsOfUse:
        return Icons.receipt_long;
      case SupportItemType.privacyPolicy:
        return Icons.lock_outline;
      }
  }

  bool _hasArrow(SupportItemType type) {
    return type == SupportItemType.question ||
        type == SupportItemType.termsOfUse ||
        type == SupportItemType.privacyPolicy;
  }

  Future<void> _launchTelUrl(String phone) async {
    final Uri phoneUri = Uri(scheme: 'tel', path: phone);
    if (await canLaunchUrl(phoneUri)) {
      await launchUrl(phoneUri);
    }
  }

  bool _isSdkSuccess(dynamic result) {
    try {
      if (result == null) return false;
      if (result is Map) {
        final status = result['status']?.toString().toLowerCase();
        return status == 'success';
      }
      if (js_util.hasProperty(result, 'status')) {
        final status = js_util.getProperty(result, 'status');
        if (status is String) {
          return status.toLowerCase() == 'success';
        }
      }
    } catch (_) {}
    return false;
  }
}
