import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:mypoint_flutter_app/directional/directional_screen.dart';
import 'package:mypoint_flutter_app/extensions/num_extension.dart';
import 'package:mypoint_flutter_app/preference/data_preference.dart';
import '../../base/base_screen.dart';
import '../../base/basic_state.dart';
import '../../directional/directional_action_type.dart';
import '../../preference/package_info.dart';
import '../../preference/point/header_home_model.dart';
import '../../resources/base_color.dart';
import '../../shared/router_gage.dart';
import '../../widgets/alert/data_alert_model.dart';
import '../home/header_home_viewmodel.dart';
import '../popup_manager/popup_runner_helper.dart';

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

  @override
  State<PersonalScreen> createState() => _PersonalScreenState();
}

class _PersonalScreenState extends BaseState<PersonalScreen> with BasicState, PopupOnInit {
  final _headerHomeVM = Get.find<HeaderHomeViewModel>();
  String? _version, _buildNumber;

  @override
  void initState() {
    super.initState();
    _loadAppInfo();
    _headerHomeVM.freshData();
    runPopupCheck(DirectionalScreenName.personal);
  }

  Future<void> _loadAppInfo() async {
    final v = await AppInfoHelper.version;
    final b = await AppInfoHelper.buildNumber;
    setState(() {
      _version = v ?? "";
      _buildNumber = b ?? "";
    });
  }

  @override
  Widget createBody() {
    return Scaffold(
      body: Column(
        children: [
          _buildHeaderPersonal(_headerHomeVM.headerData),
          Expanded(
            child: SingleChildScrollView(
              child: Column(
                children: [
                  _buildInvitationSection(),
                  _buildMenuItems(),
                  _buildVersionInfo(_version, _buildNumber),
                  Container(color: Colors.grey[200], height: MediaQuery.of(context).padding.bottom + 16),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildHeaderPersonal(HeaderHomeModel data) {
    final width = MediaQuery.of(context).size.width;
    final topPadding = MediaQuery.of(context).padding.top;
    final name = DataPreference.instance.displayName;
    final level = DataPreference.instance.rankName ?? "Hạng Đồng";
    final email = DataPreference.instance.profile?.workerSite?.email ?? "";
    return Container(
      height: width * 163 / 375,
      decoration: BoxDecoration(image: DecorationImage(image: NetworkImage(data.background ?? ""), fit: BoxFit.cover)),
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            GestureDetector(
              onTap: () async {
                await Get.toNamed(personalEditScreen);
                setState(() {});
              },
              child: Container(
                margin: EdgeInsets.only(top: topPadding),
                child: Row(
                  children: [
                    Container(
                      width: 64,
                      height: 64,
                      decoration: BoxDecoration(
                        shape: BoxShape.circle,
                        border: Border.all(color: Colors.white, width: 2),
                      ),
                      child: ClipOval(child: Image.asset("assets/images/ic_logo.png", width: 64, height: 64)),
                    ),
                    const SizedBox(width: 8),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          name,
                          style: const TextStyle(fontSize: 22, fontWeight: FontWeight.bold, color: Colors.white),
                        ),
                        if (email.isNotEmpty)
                          Text(
                            email,
                            style: const TextStyle(fontSize: 16, color: Colors.white70, fontWeight: FontWeight.w600),
                          ),
                      ],
                    ),
                    const Spacer(),
                    const Icon(Icons.chevron_right, color: Colors.white, size: 22),
                  ],
                ),
              ),
            ),
            const Spacer(),
            Row(
              children: [
                GestureDetector(
                  onTap: () {
                    Get.toNamed(membershipScreen);
                  },
                  child: Row(
                    children: [
                      Image.asset("assets/images/ic_rank_gray.png", width: 30, height: 30, color: Colors.white),
                      const SizedBox(width: 4),
                      Text(
                        level,
                        style: const TextStyle(color: Colors.white, fontSize: 16, fontWeight: FontWeight.bold),
                      ),
                    ],
                  ),
                ),
                const Spacer(),
                GestureDetector(
                  onTap: () {
                    Get.toNamed(historyPointScreen);
                  },
                  child: Row(
                    children: [
                      Text(
                        (data.totalPointActive ?? 0).money(CurrencyUnit.point),
                        style: const TextStyle(color: Colors.white, fontSize: 16, fontWeight: FontWeight.bold),
                      ),
                      const SizedBox(width: 4),
                      const Icon(Icons.chevron_right, color: Colors.white, size: 22),
                    ],
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildInvitationSection() {
    return GestureDetector(
      onTap: () {
        Get.toNamed(inviteFriendCampaignScreen);
      },
      child: Container(
        color: Colors.grey[100],
        child: Container(
          margin: const EdgeInsets.only(top: 12, bottom: 12),
          padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
          decoration: BoxDecoration(color: Colors.pink.shade50),
          child: Row(
            children: [
              Image.asset(
                'assets/images/ic_pipi_02.png',
                width: 72,
                // height: 56,
                fit: BoxFit.contain,
              ),
              const SizedBox(width: 12),
              const Expanded(
                child: Text(
                  'Mời bạn nhận quà liền tay 🎁',
                  style: TextStyle(fontSize: 16, fontWeight: FontWeight.w500, color: Colors.black87),
                ),
              ),
              const Icon(Icons.chevron_right, color: Colors.black87, size: 24),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildMenuItems() {
    final menuItems = [
      {
        'icon': Icons.monetization_on_outlined,
        'assets': 'assets/images/ic_point.png',
        'title': 'Săn điểm',
        'type': 'APP_SCREEN_POINT_HUNTING',
      },
      {'icon': Icons.qr_code_2, 'title': 'QR Code', 'type': 'APP_SCREEN_QR_CODE'},
      {'icon': Icons.check_box_outlined, 'title': 'Check-in nhận quà', 'type': 'DAILY_CHECKIN'},
      {'icon': Icons.border_right, 'title': 'Hoá đơn điện', 'type': 'APP_SCREEN_LIST_PAYMENT_OF_ELECTRIC'},
      // {'icon': Icons.emoji_events_outlined, 'title': 'Bảng xếp hạng', 'type': 'APP_SCREEN_LIST_PAYMENT_OF_ELECTRIC'},
      {'icon': Icons.gif_box_outlined, 'title': 'Ưu đãi của tôi', 'type': 'APP_SCREEN_MY_PURCHASE_ITEMS'},
      {
        'icon': Icons.receipt_long_outlined,
        'title': 'Lịch sử giao dịch',
        'sectionDivider': true,
        'type': 'APP_SCREEN_TRANSACTION_HISTORIES',
      },
      {'icon': Icons.history_outlined, 'title': 'Lịch sử điểm', 'type': 'APP_SCREEN_POINT_HISTORY'},
      {'icon': Icons.history_edu, 'title': 'Lịch sử hoàn điểm', 'type': 'APP_SCREEN_REFUND_HISTORY'},
      {'icon': Icons.account_balance_wallet_outlined, 'title': 'Quản lý tài khoản/thẻ', 'type': 'BANK_ACCOUNT_MANAGER'},
      {'icon': Icons.favorite_border, 'title': 'Yêu thích', 'type': 'APP_SCREEN_CATEGORY_TAB_FAVORITE'},
      {
        'icon': Icons.shopping_bag_outlined,
        'title': 'Đơn mua',
        'sectionDivider': true,
        'type': 'APP_SCREEN_ORDER_MENU',
      },
      {'icon': Icons.info_outline, 'title': 'Giới thiệu MyPoint', 'sectionDivider': true, 'type': 'VIEW_WEBSITE_PAGE'},
      {'icon': Icons.headset_mic_outlined, 'title': 'Hỗ trợ', 'type': 'APP_SCREEN_CUSTOMER_FEEDBACK'},
      {'icon': Icons.settings_outlined, 'title': 'Cài đặt', 'type': 'APP_SCREEN_SETTING'},
      {'icon': Icons.logout, 'title': 'Đăng xuất', 'color': Colors.red[400], 'type': 'LOGOUT'},
    ];

    return Container(
      color: Colors.white,
      child: Column(
        children:
            menuItems.map((item) {
              final needsSectionDivider = item['sectionDivider'] == true;
              return Column(
                children: [
                  if (needsSectionDivider) Container(height: 12, color: Colors.grey[100]),
                  GestureDetector(
                    onTap: () {
                      final type = item['type'] as String?;
                      if (type == "LOGOUT") {
                        _showAlertConfirmLogout();
                        return;
                      }
                      DirectionalScreen.build(clickActionType: type)?.begin();
                    },
                    child: SizedBox(
                      height: 48,
                      child: Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 16),
                        child: Row(
                          children: [
                            if (item['assets'] != null)
                              Image.asset(
                                item['assets'] as String,
                                width: 24,
                                height: 24,
                              )
                            else
                              Icon(
                                item['icon'] as IconData,
                                color: (item['color'] as Color?) ?? Colors.black54,
                                size: 24,
                              ),
                            const SizedBox(width: 12),
                            Expanded(
                              child: Text(
                                item['title'] as String,
                                style: TextStyle(
                                  fontSize: 16,
                                  fontWeight: FontWeight.w500,
                                  color: (item['color'] as Color?) ?? Colors.black87,
                                ),
                              ),
                            ),
                            const Icon(Icons.chevron_right, color: Colors.black54, size: 24),
                          ],
                        ),
                      ),
                    ),
                  ),
                ],
              );
            }).toList(),
      ),
    );
  }

  _buildVersionInfo(String? version, String? buildNumber) {
    return Container(
      color: Colors.grey[200],
      padding: const EdgeInsets.symmetric(vertical: 12),
      alignment: Alignment.center,
      child: Text(
        "Phiên bản: $version($buildNumber)",
        style: TextStyle(color: Colors.black87, fontSize: 14, fontWeight: FontWeight.bold),
      ),
    );
  }

  _showAlertConfirmLogout() {
    final dataAlert = DataAlertModel(
      title: "Xác nhận",
      description: "Bạn có chắc muốn đăng xuất?",
      localHeaderImage: "assets/images/ic_pipi_03.png",
      buttons: [
        AlertButton(
          text: "Đồng ý",
          onPressed: () {
            DataPreference.instance.clearLoginToken();
            _safeBackToLogin();
          },
          bgColor: BaseColor.primary500,
          textColor: Colors.white,
        ),
        AlertButton(text: "Huỷ", onPressed: () => Get.back(), bgColor: Colors.white, textColor: BaseColor.second500),
      ],
    );
    showAlert(data: dataAlert);
  }

  void _safeBackToLogin() {
    bool found = false;
    Navigator.popUntil(Get.context!, (route) {
      final matched = route.settings.name == loginScreen;
      if (matched) found = true;
      return matched;
    });
    final phone = DataPreference.instance.phoneNumberUsedForLoginScreen;
    final displayName = DataPreference.instance.displayName;
    print("Safe back to login screen with phone: $phone, displayName: $displayName, found: $found");
    if (phone != null && found) {
      Get.offAllNamed(loginScreen, arguments: {"phone": phone, 'fullName': displayName});
    } else {
      DataPreference.instance.clearData();
      Get.offAllNamed(onboardingScreen);
    }
  }
}
