import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_contacts/flutter_contacts.dart';
import 'package:get/get.dart';
import 'package:mypoint_flutter_app/shared/widgets/custom_empty_widget.dart';
import 'package:share_plus/share_plus.dart';
import 'package:url_launcher/url_launcher.dart';
import '../../../features/invite_friend_campaign/popup_invite_friend_code.dart';
import '../../../shared/widgets/custom_toast_message.dart';
import '../../app/config/constants.dart';
import '../../shared/widgets/base_view/base_screen.dart';
import '../../shared/widgets/base_view/basic_state.dart';
import '../../core/theme/base_color.dart';
import '../../shared/router_gage.dart';
import '../../shared/widgets/custom_navigation_bar.dart';
import '../../shared/widgets/image_loader.dart';
import 'invite_friend_campaign_viewmodel.dart';
import 'models/invite_friend_campaign_model.dart';

class InviteFriendCampaignScreen extends BaseScreen {
  const InviteFriendCampaignScreen({super.key});

  @override
  State<InviteFriendCampaignScreen> createState() => _InviteFriendCampaignScreenState();
}

class _InviteFriendCampaignScreenState extends BaseState<InviteFriendCampaignScreen> with BasicState {
  final InviteFriendCampaignViewModel viewModel = Get.put(InviteFriendCampaignViewModel());
  List<Contact> contacts = [];

  @override
  void initState() {
    super.initState();
    fetchContacts();
    viewModel.onShowAlertError = (message, onBack) {
      if (message.isNotEmpty) {
        showAlertError(content: message, onConfirmed: onBack ? () => Get.back() : null, showCloseButton: !onBack);
      }
    };
    viewModel.phoneInviteFriendResponse = (sms, phone) {
      _openSMS(sms, phone);
    };
    viewModel.loadData();
  }

  Future<void> _openSMS(String sms, String phone) async {
    final uri = Uri(scheme: 'sms', path: phone, queryParameters: <String, String>{'body': sms});

    if (await canLaunchUrl(uri)) {
      await launchUrl(uri);
    }
  }

  @override
  Widget createBody() {
    return Scaffold(
      appBar: PreferredSize(
        preferredSize: Size.fromHeight(kToolbarHeight + Constants.extendTopPaddingNavigation),
        child: Obx(() {
          final title = viewModel.inviteFriendDetail.value?.name ?? 'Mời bạn bè';
          return CustomNavigationBar(title: title);
        }),
      ),
      backgroundColor: Color(0xFFFDE8EA),
      body: SingleChildScrollView(
        child: Obx(() {
          return Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              if (viewModel.inviteFriendDetail.value != null) ...[
                _buildHeaderInfo(),
                SizedBox(height: 56),
                _buildInviteCardBox(),
              ],
              if (viewModel.inviteFriendDetail.value == null) ...[
                SizedBox(height: 16),
                EmptyWidget(isLoading: viewModel.isLoading.value),
                SizedBox(height: 16),
              ],
              _buildContactCardBox(),
              _buildCampaignBox(),
              Container(color: Colors.grey.shade100, child: SizedBox(height: 64)),
            ],
          );
        }),
      ),
    );
  }

  Future<void> fetchContacts() async {
    if (!await FlutterContacts.requestPermission()) {
      debugPrint("🚫 Không có quyền");
      return;
    }
    final contacts = await FlutterContacts.getContacts(withProperties: true);
    debugPrint("📋 Số lượng liên hệ: ${contacts.length}");
    setState(() {
      this.contacts = contacts;
    });
  }

  Widget _buildHeaderInfo() {
    final double screenWidth = MediaQuery.of(context).size.width;
    final double imageHeight = screenWidth / (16 / 9);
    return Obx(() {
      return Stack(
        clipBehavior: Clip.none,
        children: [
          loadNetworkImage(
            url: viewModel.inviteFriendDetail.value?.bannerUrl,
            fit: BoxFit.fill,
            height: imageHeight,
            width: double.infinity,
            placeholderAsset: 'assets/images/bg_header_detail_brand.png',
          ),
          Positioned(
            top: 12,
            left: 16,
            right: 16,
            child: GestureDetector(
              onTap: () {
                Get.toNamed(referralCodeInviteFriendScreen, arguments: {
                  'title': viewModel.inviteFriendDetail.value?.name ?? 'Mã giới thiệu'
                });
              },
              child: Container(
                height: 42,
                decoration: BoxDecoration(
                  color: Colors.transparent,
                  border: Border.all(color: BaseColor.primary500),
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Row(
                  children: [
                    const SizedBox(width: 8),
                    Icon(Icons.person_add_alt_sharp, color: Colors.black54),
                    const SizedBox(width: 8),
                    const Text(
                      'Nhập mã giới thiệu bạn bè ở đây',
                      style: TextStyle(fontSize: 14, color: Colors.black87),
                    ),
                  ],
                ),
              ),
            ),
          ),
          Positioned(
            left: 16,
            right: 16,
            child: Transform.translate(offset: Offset(0, imageHeight - 36), child: _buildInfoCard()),
          ),
        ],
      );
    });
  }

  Widget _buildInfoCard() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        boxShadow: const [BoxShadow(color: Colors.black12, blurRadius: 4, offset: Offset(0, 2))],
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            viewModel.inviteFriendDetail.value?.reward?.title ?? '',
            style: const TextStyle(fontWeight: FontWeight.w800, fontSize: 18),
          ),
          const SizedBox(height: 8),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: _buildRewardWidgets(viewModel.inviteFriendDetail.value?.reward?.rewards ?? []),
          ),
        ],
      ),
    );
  }

  List<Widget> _buildRewardWidgets(List<RewardInviteItemModel>? rewards) {
    if (rewards == null || rewards.isEmpty) {
      return [];
    }
    return rewards.map((e) => _rewardItem(e)).toList();
  }

  Widget _rewardItem(RewardInviteItemModel item) {
    return Row(
      children: [
        loadNetworkImage(url: item.icon, width: 24, height: 24, placeholderAsset: "assets/images/ic_point.png"),
        const SizedBox(width: 4),
        Text(item.quantity.toString(), style: const TextStyle(fontWeight: FontWeight.bold)),
      ],
    );
  }

  Widget _buildInviteCardBox() {
    return Obx(() {
      return Container(
        margin: const EdgeInsets.all(16),
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(12)),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text('Gửi mã giới thiệu cho bạn bè', style: TextStyle(fontSize: 18, fontWeight: FontWeight.w800)),
            const SizedBox(height: 12),
            const Text(
              'Mã giới thiệu',
              style: TextStyle(fontSize: 14, color: Colors.black87, fontWeight: FontWeight.w600),
            ),
            const SizedBox(height: 4),
            Container(
              height: 48,
              padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
              decoration: BoxDecoration(color: Colors.grey.shade200, borderRadius: BorderRadius.circular(8)),
              child: Row(
                children: [
                  Expanded(
                    child: Text(
                      viewModel.inviteFriendDetail.value?.inviteCodeDefault ?? '',
                      style: const TextStyle(fontWeight: FontWeight.bold, color: BaseColor.primary500, fontSize: 16),
                    ),
                  ),
                  GestureDetector(
                    onTap: () {
                      Clipboard.setData(
                        ClipboardData(text: viewModel.inviteFriendDetail.value?.inviteCodeDefault ?? ''),
                      );
                      showToastMessage('Đã sao chép');
                    },
                    child: SizedBox(
                      width: 40,
                      height: double.infinity,
                      child: Center(child: Icon(Icons.copy, color: BaseColor.primary500, size: 20)),
                    ),
                  ),
                ],
              ),
            ),
            const SizedBox(height: 12),
            const Text(
              'Hoặc chia sẻ qua',
              style: TextStyle(fontSize: 14, color: Colors.black87, fontWeight: FontWeight.w600),
            ),
            const SizedBox(height: 4),
            Row(
              children: [
                Expanded(
                  child: ElevatedButton.icon(
                    onPressed: () {
                      showPopupInviteFriendCode(context, viewModel.inviteFriendDetail.value?.inviteCodeDefault ?? '');
                    },
                    style: ElevatedButton.styleFrom(
                      backgroundColor: BaseColor.primary500,
                      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
                    ),
                    icon: const Icon(Icons.qr_code, color: Colors.white),
                    label: const Text('QR code', style: TextStyle(color: Colors.white)),
                  ),
                ),
                const SizedBox(width: 12),
                Expanded(
                  child: OutlinedButton.icon(
                    onPressed: () {
                      final content = viewModel.inviteFriendDetail.value?.shareContent ?? '';
                      if (content.isEmpty) return;
                      Share.share(content);
                    },
                    style: OutlinedButton.styleFrom(
                      side: const BorderSide(color: BaseColor.primary500),
                      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
                    ),
                    icon: const Icon(Icons.share, color: BaseColor.primary500),
                    label: const Text('Chia sẻ', style: TextStyle(color: BaseColor.primary500)),
                  ),
                ),
              ],
            ),
          ],
        ),
      );
    });
  }

  Widget _buildContactCardBox() {
    const maxItems = 7;
    final displayedContacts = contacts.take(maxItems).toList();
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16),
      decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(12)),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                const Text('Danh bạ', style: TextStyle(fontSize: 18, fontWeight: FontWeight.w800)),
                GestureDetector(
                  onTap: () {
                    Get.toNamed(contactsListScreen, arguments: {'contacts': contacts});
                  },
                  child: Text(
                    'Xem tất cả',
                    style: TextStyle(color: BaseColor.primary500, fontSize: 14, fontWeight: FontWeight.w700),
                  ),
                ),
              ],
            ),
          ),

          ...List.generate(displayedContacts.length, (index) {
            final contact = displayedContacts[index];
            final name = contact.displayName;
            final phone = contact.phones.firstOrNull?.number ?? 'Không số';
            return Column(
              children: [
                if (index != 0) const Divider(height: 1, color: Colors.black12, indent: 16, endIndent: 16),
                ListTile(
                  leading: const CircleAvatar(
                    backgroundImage: AssetImage('assets/images/ic_pipi_02.png'),
                    backgroundColor: BaseColor.primary200,
                  ),
                  title: Text(name, style: const TextStyle(fontWeight: FontWeight.bold)),
                  subtitle: Text(phone),
                  trailing: OutlinedButton(
                    style: OutlinedButton.styleFrom(
                      side: const BorderSide(color: BaseColor.primary500, width: 1.5),
                      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
                    ),
                    onPressed: () {
                      viewModel.phoneInviteFriend(phone);
                    },
                    child: const Text(
                      'Mời',
                      style: TextStyle(color: BaseColor.primary500, fontWeight: FontWeight.w800),
                    ),
                  ),
                ),
              ],
            );
          }),
        ],
      ),
    );
  }

  Widget _buildCampaignBox() {
    final detail = viewModel.campaignDetail.value;
    final campaigns = detail?.campaigns ?? [];
    return campaigns.isEmpty
        ? SizedBox()
        : Container(
          margin: const EdgeInsets.all(16),
          padding: const EdgeInsets.all(12),
          decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(12)),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              if ((detail?.title ?? '').isNotEmpty)
                Text(
                  detail?.title ?? '',
                  maxLines: 1,
                  style: const TextStyle(fontSize: 18, fontWeight: FontWeight.w800),
                ),
              const SizedBox(height: 12),
              ListView.separated(
                shrinkWrap: true,
                physics: const NeverScrollableScrollPhysics(),
                itemCount: campaigns.length,
                separatorBuilder: (_, _) => const SizedBox(height: 8),
                itemBuilder: (context, index) {
                  final campaign = campaigns[index];
                  return Container(
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(8),
                      border: Border.all(color: Colors.grey.shade300),
                    ),
                    padding: const EdgeInsets.all(8),
                    child: Row(
                      children: [
                        ClipRRect(
                          borderRadius: BorderRadius.circular(8),
                          child: loadNetworkImage(
                            url: campaign.avatarUrl,
                            width: 82,
                            height: 82,
                            placeholderAsset: "assets/images/bg_default_11.png",
                          ),
                        ),
                        const SizedBox(width: 12),
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                campaign.name ?? '',
                                maxLines: 2,
                                style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 14),
                              ),
                              const SizedBox(height: 4),
                              Text(
                                campaign.description ?? '',
                                maxLines: 2,
                                style: const TextStyle(fontSize: 12, color: Colors.black54),
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  );
                },
              ),
            ],
          ),
        );
  }
}
