import 'dart:async';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../../core/utils/extensions/string_extension.dart';
import '../../../features/invite_friend_campaign/referral_code_invite_friend/referral_code_invite_friend_viewmodel.dart';
import '../../../shared/router_gage.dart';
import '../../../shared/widgets/alert/custom_alert_dialog.dart';
import '../../../shared/widgets/alert/data_alert_model.dart';
import '../../../shared/widgets/custom_empty_widget.dart';
import '../../../core/theme/base_color.dart';
import '../../../shared/widgets/base_view/base_screen.dart';
import '../../../shared/widgets/base_view/basic_state.dart';
import '../../../shared/widgets/custom_navigation_bar.dart';
import '../../../shared/widgets/image_loader.dart';
import '../models/invite_friend_campaign_model.dart';

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

  @override
  State<ReferralCodeInviteFriendScreen> createState() => _ReferralCodeInviteFriendScreenState();
}

class _ReferralCodeInviteFriendScreenState extends BaseState<ReferralCodeInviteFriendScreen> with BasicState {
  final ReferralCodeInviteFriendViewModel viewModel = Get.put(ReferralCodeInviteFriendViewModel());
  final TextEditingController _codeController = TextEditingController();
  Timer? _debounce;
  String _title = 'Mời bạn bè';

  void _onCodeChanged(String value) {
    setState(() {});
    _debounce?.cancel();
    final code = value.trim();
    if (code.isEmpty) {
      viewModel.referralCampaignData.value = null;
      return;
    }
    _debounce = Timer(const Duration(seconds: 1), () {
      viewModel.getCampaignReferralCodeInvite(code);
    });
  }

  void _clearCode() {
    _debounce?.cancel();
    _codeController.clear();
    viewModel.referralCampaignData.value = null;
    setState(() {});
  }

  @override
  void initState() {
    super.initState();
    final args = Get.arguments;
    if (args is Map) {
      _title = args['title'];
    }
    viewModel.getCampaignReferralCodeInvite('');
    viewModel.onShowAlertError = (message) {
      showAlertError(content: message);
    };
    viewModel.acceptCampaignResponse = (data) {
      final popup = DataAlertModel(
        title: data.title ?? 'Nhận lời mời thành công',
        description: data.content ?? 'Hãy thực hiện nhiệm vụ và xem trạng thái nhận quà trong mục lịch sử',
        localHeaderImage: 'assets/images/ic_pipi_05.png',
        buttons: [
          AlertButton(
            text: 'Đóng',
            onPressed: () {
              Get.back();
            },
            bgColor: BaseColor.second300,
            textColor: Colors.white,
          ),
          AlertButton(
            text: 'Thực hiện',
            onPressed: () {
              WidgetsBinding.instance.addPostFrameCallback((_) {
                Get.back();
                data.directionalScreen?.begin();
              });
            },
            bgColor: BaseColor.primary500,
            textColor: Colors.white,
          ),
        ],
      );
      showAlert(data: popup, direction: ButtonsDirection.row);
    };
  }

  @override
  void dispose() {
    _debounce?.cancel();
    _codeController.dispose();
    super.dispose();
  }

  @override
  Widget createBody() {
    return Scaffold(
      appBar: CustomNavigationBar(title: _title),
      body: Column(
        children: [
          _buildCodeInput(),
          Expanded(
            child: Obx(() {
              final detail = viewModel.referralCampaignData.value;
              final campaigns = detail?.campaigns ?? [];
              if (campaigns.isEmpty) {
                return Center(child: EmptyWidget(isLoading: viewModel.isLoading.value));
              }
              return SingleChildScrollView(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    _buildCampaignBox(detail, campaigns),
                    Container(color: Colors.grey.shade100, child: const SizedBox(height: 64)),
                  ],
                ),
              );
            }),
          ),
        ],
      ),
    );
  }

  Widget _buildCodeInput() {
    return Padding(
      padding: const EdgeInsets.all(16),
      child: Container(
        decoration: BoxDecoration(
          // color: Colors.white,
          color: Color(0xFFFDE8EA),
          border: Border.all(color: BaseColor.primary500),
          borderRadius: BorderRadius.circular(12),
        ),
        child: TextField(
          controller: _codeController,
          onChanged: _onCodeChanged,
          decoration: InputDecoration(
            prefixIcon: Icon(Icons.person_add_alt_sharp, color: Colors.black),
            hintText: 'Nhập mã giới thiệu bạn bè ở đây',
            suffixIcon:
                _codeController.text.isEmpty
                    ? null
                    : IconButton(icon: Icon(Icons.close, color: Colors.black), onPressed: _clearCode),
            border: InputBorder.none,
            contentPadding: const EdgeInsets.symmetric(vertical: 12, horizontal: 8),
          ),
        ),
      ),
    );
  }

  Widget _buildCampaignBox(CampaignInviteFriendDetail? detail, List<CampaignInviteFriendItemModel> campaigns) {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16),
      decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(12)),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if ((detail?.title ?? '').isNotEmpty)
            Padding(
              padding: const EdgeInsets.fromLTRB(0, 8, 8, 0),
              child: Text(
                detail?.title ?? '',
                maxLines: 1,
                style: const TextStyle(fontSize: 18, fontWeight: FontWeight.w800),
              ),
            ),
          ListView.separated(
            shrinkWrap: true,
            padding: const EdgeInsets.symmetric(vertical: 4),
            physics: const NeverScrollableScrollPhysics(),
            itemCount: campaigns.length,
            separatorBuilder: (_, _) => Divider(height: 1, color: Colors.grey.shade200),
            itemBuilder: (context, index) {
              final campaign = campaigns[index];
              return GestureDetector(
                behavior: HitTestBehavior.opaque,
                onTap: () {
                  final code = _codeController.text.trim();
                  Get.toNamed(campaignInviteReferralInfoScreen, arguments: {'id': campaign.id ?? '', 'code': code});
                  print('Tap campaign: ${campaign.id}' );
                },
                child: Container(
                  padding: const EdgeInsets.symmetric(vertical: 12),
                  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: 8),
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            if (campaign.name.orEmpty.isNotEmpty)
                              Text(
                                campaign.name ?? '',
                                maxLines: 2,
                                style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 14),
                              ),
                            if (campaign.name.orEmpty.isNotEmpty) ...[
                              const SizedBox(height: 4),
                              Text(
                                campaign.description ?? '',
                                maxLines: 2,
                                style: const TextStyle(fontSize: 12, color: Colors.black54),
                              ),
                            ],
                          ],
                        ),
                      ),
                      const SizedBox(width: 8),
                      OutlinedButton(
                        style: OutlinedButton.styleFrom(
                          side: const BorderSide(color: BaseColor.primary500, width: 1.5),
                          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
                          padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                          backgroundColor: BaseColor.primary500,
                        ),
                        onPressed: () {
                          viewModel.acceptCampaign(campaign, _codeController.text.trim());
                        },
                        child: const Text(
                          'Nhận lời mời',
                          style: TextStyle(color: Colors.white, fontWeight: FontWeight.w600, fontSize: 13),
                        ),
                      ),
                    ],
                  ),
                ),
              );
            },
          ),
        ],
      ),
    );
  }
}
