// delete_account_dialog.dart
import 'package:flutter/material.dart';
import 'package:flutter/gestures.dart';
import 'package:get/get.dart';
import 'package:mypoint_flutter_app/preference/data_preference.dart';
import '../../preference/point/point_manager.dart';
import '../../resources/button_style.dart';
import '../../resources/text_style.dart';
import '../../shared/router_gage.dart';
import '../pageDetail/campaign_detail_screen.dart';
import '../pageDetail/model/detail_page_rule_type.dart';
import 'delete_account_viewmodel.dart';

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

  @override
  State<DeleteAccountDialog> createState() => _DeleteAccountDialogState();
}

class _DeleteAccountDialogState extends State<DeleteAccountDialog> {
  final DeleteAccountViewModel _viewModel = DeleteAccountViewModel();
  late TapGestureRecognizer _termConditionRecognizer;

  @override
  void initState() {
    super.initState();
    _termConditionRecognizer = TapGestureRecognizer()..onTap = _onTermConditionPressed;
  }

  @override
  void dispose() {
    _termConditionRecognizer.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final int userPoints = UserPointManager().point;

    return Padding(
      padding: const EdgeInsets.fromLTRB(8, 0, 8, 32),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Image.asset('assets/images/ic_pipi_03.png', height: 220),
          const SizedBox(height: 16),
          Text("Bạn có chắc chắn muốn xoá tài khoản?", style: AppTextStyle.title, textAlign: TextAlign.center),
          const SizedBox(height: 12),
          RichText(
            textAlign: TextAlign.center,
            text: TextSpan(
              style: AppTextStyle.content,
              children: [
                const TextSpan(text: "Toàn bộ "),
                TextSpan(text: "$userPoints điểm ", style: AppTextStyle.boldContent),
                const TextSpan(text: "và " ),
                WidgetSpan(
                  child: GestureDetector(
                    onTap: _onUnUsedVoucherPressed,
                    child: Text(
                      "Ưu đãi chưa sử dụng ",
                      style: AppTextStyle.link.copyWith(
                        color: Colors.blue,                              // ✅ Màu chữ
                        decoration: TextDecoration.underline,           // ✅ Gạch chân
                        decorationColor: Colors.blue,                   // ✅ Gạch chân màu xanh
                      ),
                    ),
                  ),
                ),
                const TextSpan(text: "sẽ bị mất và bạn không thể đăng ký lại tài khoản trong vòng "),
                const TextSpan(text: "30 ngày", style: AppTextStyle.boldContent),
                const TextSpan(text: " kể từ thời điểm xoá."),
              ],
            ),
          ),
          const SizedBox(height: 16),
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Theme(
                data: Theme.of(context).copyWith(
                  checkboxTheme: CheckboxThemeData(
                    fillColor: MaterialStateProperty.resolveWith<Color>((states) {
                      if (states.contains(MaterialState.selected)) {
                        return Colors.red; // ✅ Checked: màu đỏ
                      }
                      return Colors.white; // ❌ Unchecked: ô trắng
                    }),
                    checkColor: MaterialStateProperty.all(Colors.white), // ✅ Tick màu trắng
                    side: const BorderSide(color: Colors.grey),
                  ),
                ),
                child: Checkbox(
                  value: _viewModel.agreed.value,
                  onChanged: (value) => setState(() => _viewModel.agreed.value = value ?? false),
                  visualDensity: const VisualDensity(horizontal: -4, vertical: -4),
                ),
              ),
              const SizedBox(width: 8),
              Expanded(
                child: RichText(
                  text: TextSpan(
                    style: AppTextStyle.content,
                    children: [
                      const TextSpan(text: "Tôi đã đọc và đồng ý với "),
                      TextSpan(
                        text: "Điều khoản xoá tài khoản của MyPoint.",
                        style: AppTextStyle.link.copyWith(color: Colors.blue, decoration: TextDecoration.underline),
                        recognizer: _termConditionRecognizer,
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
          const SizedBox(height: 16),
          SizedBox(
            width: double.infinity,
            height: 40,
            child: ElevatedButton(
              onPressed: _viewModel.agreed.value ? _onConfirmDelete : null,
              style: AppButtonStyle.secondary,
              child: const Text("Xác nhận xoá"),
            ),
          ),
          const SizedBox(height: 8),
          SizedBox(
            width: double.infinity,
            height: 40,
            child: ElevatedButton(
              onPressed: () => Get.back(),
              style: AppButtonStyle.primary,
              child: const Text("Để sau"),
            ),
          ),
        ],
      ),
    );
  }

  void _onConfirmDelete() {
    if (DataPreference.instance.profile?.userAgreements?.hideDeleteAccount == false) {
      _viewModel.confirmDelete();
    } else {
      DataPreference.instance.clearData();
      Get.offAllNamed(onboardingScreen);
    }
  }

  void _onUnUsedVoucherPressed() {
    print("Đi đến màn hình ưu đãi chưa sử dụng");
    // TODO: Get.toNamed('/unused-voucher'); hoặc mở webview
  }

  void _onTermConditionPressed() {
    Get.toNamed(campaignDetailScreen, arguments: {"type": DetailPageRuleType.policyDeleteAccount});
  }
}
