import 'dart:io';

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:getx_scaffold/common/index.dart';
import 'package:getx_scaffold/common/widgets/index.dart';
import 'package:ln_jq_app/common/login_util.dart';
import 'package:ln_jq_app/common/styles/theme.dart';
import 'package:ln_jq_app/pages/c_page/message/view.dart';
import 'package:ln_jq_app/pages/common/webview/view.dart';
import 'package:ln_jq_app/storage_service.dart';
import 'controller.dart';

class MinePage extends GetView<MineController> {
  const MinePage({super.key});

  @override
  Widget build(BuildContext context) {
    return GetBuilder<MineController>(
      init: MineController(),
      id: 'mine',
      builder: (_) {
        return Scaffold(
          backgroundColor: const Color.fromRGBO(247, 249, 251, 1),
          body: SingleChildScrollView(
            child: Column(
              children: [
                _buildUserInfoCard(),
                const SizedBox(height: 8),
                // 新 UI 模块开始
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 20.0),
                  child: Column(
                    children: [
                      _buildWalletCard(),
                      SizedBox(height: 16.h),
                      _buildGridMenu(),
                      SizedBox(height: 16.h),
                      _buildRecommendCard(context),
                      SizedBox(height: 8.h),
                      _buildSafetyReminderCard(),
                      SizedBox(height: 24.h),
                      _buildLogoutButton(),
                      SizedBox(height: 15.h),
                      Text.rich(
                        TextSpan(
                          style: const TextStyle(color: Colors.grey, fontSize: 13),
                          children: [
                            TextSpan(
                              text: '《用户协议》',
                              style: TextStyle(color: Colors.blue, fontSize: 13),
                              recognizer: TapGestureRecognizer()
                                ..onTap = () {
                                  openPage("用户协议", "https://lnh2e.com/user_agreement.html");
                                },
                            ),
                            TextSpan(
                              text: '《隐私政策》',
                              style: TextStyle(color: Colors.blue, fontSize: 13),
                              recognizer: TapGestureRecognizer()
                                ..onTap = () {
                                  openPage("隐私政策", "https://lnh2e.com/privacy_agreement.html");
                                },
                            ),
                          ],
                        ),
                      ),
                      SizedBox(height: 95.h),
                    ],
                  ),
                ),
                // 新 UI 模块结束
              ],
            ),
          ),
        );
      },
    );
  }

  void openPage(String title, String url) {
    if (Platform.isIOS) {
      openWebPage(url);
      return;
    }
    Get.to(() => const WebViewPage(), arguments: {'title': title, 'url': url});
  }


  ///  构建顶部用户信息卡片
  Widget _buildUserInfoCard() {
    return Card(
      elevation: 1,
      color: Colors.white,
      margin: EdgeInsets.zero,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.only(
          bottomLeft: Radius.circular(20),
          bottomRight: Radius.circular(20),
        ),
      ),
      child: Column(
        children: [
          Padding(
            padding: EdgeInsets.only(left: 20.w, right: 20.w, bottom: 16, top: 40),
            // 增加了顶部 padding 适配状态栏
            child: Row(
              children: [
                Stack(
                  children: [
                    CircleAvatar(
                      radius: 25,
                      backgroundColor: Colors.white,
                      child: LoginUtil.getAssImg('ic_user_logo@2x'),
                    ),
                    Positioned(
                      right: 0,
                      bottom: 0,
                      child: SizedBox(
                        height: 16.h,
                        width: 16.w,
                        child: LoginUtil.getAssImg('ic_logo@2x'),
                      ),
                    ),
                  ],
                ),
                SizedBox(width: 8.w),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          Text(
                            "${StorageService.to.name}",
                            style: const TextStyle(
                              fontSize: 14,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          SizedBox(width: 8.w),
                          Container(
                            padding: const EdgeInsets.symmetric(
                              horizontal: 8,
                              vertical: 2,
                            ),
                            decoration: BoxDecoration(
                              color: const Color.fromRGBO(236, 255, 234, 1), // 极浅绿色背景
                              border: Border.all(color: const Color(0xFFB7E19F)), // 边框
                              borderRadius: BorderRadius.circular(12),
                            ),
                            child: const Row(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                Icon(Icons.eco, size: 12, color: Color(0xFF52C41A)),
                                // 叶子图标
                                SizedBox(width: 4),
                                Text(
                                  "绿色先锋",
                                  style: TextStyle(
                                    color: Color(0xFF52C41A),
                                    fontSize: 10,
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                      const SizedBox(height: 4),
                      Text(
                        "羚牛ID：${StorageService.to.phone}",
                        style: const TextStyle(color: Colors.grey, fontSize: 11),
                      ),
                    ],
                  ),
                ),
                IconButton(
                  onPressed: () async{
                    var scanResult = await Get.to(() => const MessagePage());
                    if (scanResult == null) {
                      controller.msgNotice();
                    }

                  },
                  style: IconButton.styleFrom(
                    backgroundColor: Colors.grey[100],
                    padding: const EdgeInsets.all(8),
                  ),
                  icon: Badge(
                    smallSize: 8,
                    backgroundColor: controller.isNotice
                        ? Colors.red
                        : Colors.transparent,
                    child: const Icon(
                      Icons.notifications_outlined,
                      color: Colors.black87,
                      size: 30,
                    ),
                  ),
                ),
              ],
            ),
          ),
          Padding(
            padding: EdgeInsets.only(left: 20.w, right: 20.w, bottom: 20),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                _buildModernStatItem('服务天数', 'service days', '156', ''),
                const SizedBox(width: 8),
                _buildModernStatItem('准时率', 'Punctuality', controller.rate, ''),
                const SizedBox(width: 8),
                _buildModernStatItem('司机评分', 'Driver rating', controller.rating, ''),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // 统计项
  Widget _buildModernStatItem(String title, String subtitle, String value, String unit) {
    return Expanded(
      child: Container(
        padding: const EdgeInsets.all(12.0),
        decoration: BoxDecoration(
          color: const Color(0xFFF8F9FA),
          borderRadius: BorderRadius.circular(12),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              title,
              style: const TextStyle(
                fontSize: 12,
                fontWeight: FontWeight.bold,
                color: Colors.black87,
              ),
            ),
            Text(subtitle, style: const TextStyle(fontSize: 9, color: Colors.grey)),
            const SizedBox(height: 8),
            Row(
              crossAxisAlignment: CrossAxisAlignment.baseline,
              textBaseline: TextBaseline.alphabetic,
              children: [
                Text(
                  value,
                  style: const TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w600,
                    color: Colors.black87,
                  ),
                ),
                Text(unit, style: const TextStyle(fontSize: 10, color: Colors.black54)),
              ],
            ),
          ],
        ),
      ),
    );
  }

  /// 我的钱包卡片
  Widget _buildWalletCard() {
    return Card(
      elevation: 1,
      color: Colors.white,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Row(
          children: [
            const Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    "我的钱包",
                    style: TextStyle(fontSize: 15, fontWeight: FontWeight.bold),
                  ),
                  Text("User wallet", style: TextStyle(fontSize: 12, color: Colors.grey)),
                ],
              ),
            ),
            Text(
              "¥ 0,00元",
              style: TextStyle(
                color: Colors.green[700],
                fontSize: 16,
                fontWeight: FontWeight.bold,
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 2x2 功能网格菜单
  Widget _buildGridMenu() {
    return Column(
      children: [
        Row(
          children: [
            _buildGridItem(Icons.person_search_outlined, "客服评价", "3项可评"),
            const SizedBox(width: 19),
            _buildGridItem(
              Icons.assignment_late_outlined,
              "违章处理",
              "${controller.historyBreakRules}项待办",
              countColor: Colors.red,
            ),
          ],
        ),
        const SizedBox(height: 16),
        Row(
          children: [
            _buildGridItem(Icons.book_outlined, "安全培训", "0个待看"),
            const SizedBox(width: 19),
            _buildGridItem(
              Icons.verified_user_outlined,
              "诚信加氢值",
              "845",
              isSpecial: true,
              backgroundColor: const Color(0xFF006633),
            ),
          ],
        ),
      ],
    );
  }

  Widget _buildGridItem(
    IconData icon,
    String title,
    String subtitle, {
    Color? countColor,
    bool isSpecial = false,
    Color? backgroundColor,
  }) {
    return Expanded(
      child: Container(
        height: 100,
        padding: const EdgeInsets.all(12),
        decoration: BoxDecoration(
          color: isSpecial ? backgroundColor : Colors.white,
          borderRadius: BorderRadius.circular(16),
        ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(icon, color: isSpecial ? Colors.white : Colors.black87, size: 28),
            const SizedBox(height: 8),
            Text(
              title,
              style: TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.bold,
                color: isSpecial ? Colors.white : Colors.black87,
              ),
            ),
            Text(
              subtitle,
              style: TextStyle(
                fontSize: 12,
                color: isSpecial
                    ? Colors.white.withOpacity(0.8)
                    : (countColor ?? Colors.grey),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 我要推荐卡片
  Widget _buildRecommendCard(BuildContext context) {
    return Card(
      elevation: 0,
      color: Colors.white,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
      child: Padding(
        padding: const EdgeInsets.all(12.0),
        child: Column(
          children: [
            const Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      "我要推荐",
                      style: TextStyle(fontSize: 15, fontWeight: FontWeight.bold),
                    ),
                    Text("Recommend", style: TextStyle(fontSize: 12, color: Colors.grey)),
                  ],
                ),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    Text("累计奖励(积分)", style: TextStyle(fontSize: 11, color: Colors.grey)),
                    Text(
                      "0,00",
                      style: TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                        color: Colors.green,
                      ),
                    ),
                  ],
                ),
              ],
            ),
            const SizedBox(height: 16),
            ElevatedButton(
              onPressed: () {
                if (GetPlatform.isIOS) {
                  // 跳转到 iOS 应用商店 (这里使用一个通用的应用商店链接模板，请确保替换为正式的 AppID)
                  openWebPage("https://apps.apple.com/cn/app/羚牛氢能/6756245815");
                } else if (GetPlatform.isAndroid) {
                  // Android 弹出二维码图片
                  _showAndroidDownloadDialog(context);
                }
              },
              style: ElevatedButton.styleFrom(
                backgroundColor: const Color(0xFF006633),
                foregroundColor: Colors.white,
                minimumSize: const Size(double.infinity, 48),
                shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(24)),
                elevation: 0,
              ),
              child: const Text(
                "下载推荐",
                style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// Android 端下载二维码弹窗
  void _showAndroidDownloadDialog(BuildContext context) {
    Get.dialog(
      Center(
        child: Container(
          width: 280.w,
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(16),
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Padding(
                padding: const EdgeInsets.all(24.0),
                child: Column(
                  children: [
                    const Text(
                      "扫描二维码下载",
                      style: TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                        color: Colors.black87,
                      ),
                    ),
                    const SizedBox(height: 20),
                    // 使用 LoginUtil.getAssImg 加载你的图片 android_apk_img.png
                    SizedBox(
                      width: 180.w,
                      height: 180.w,
                      child: LoginUtil.getAssImg('android_apk_img'),
                    ),
                    const SizedBox(height: 16),
                    const Text(
                      "请让被推荐人扫描上方二维码进行下载安装",
                      textAlign: TextAlign.center,
                      style: TextStyle(fontSize: 13, color: Colors.grey),
                    ),
                  ],
                ),
              ),
              const Divider(height: 1),
              TextButton(
                onPressed: () => Get.back(),
                style: TextButton.styleFrom(minimumSize: const Size(double.infinity, 50)),
                child: const Text(
                  "确 定",
                  style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 安全提醒卡片
  Widget _buildSafetyReminderCard() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: const Color.fromRGBO(242, 249, 248, 1), // 极浅绿色背景
        borderRadius: BorderRadius.circular(16),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Icon(Icons.info_outline, color: Colors.green[700], size: 24),
              const SizedBox(width: 8),
              Text(
                "安全提醒",
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                  color: Colors.green[900],
                ),
              ),
            ],
          ),
          const SizedBox(height: 12),
          Text(
            "请保持良好驾驶习惯，提高安全评分，遵守交通规则，避免违章扣分。",
            style: TextStyle(fontSize: 13, color: Colors.green[800], height: 1.5),
          ),
          const SizedBox(height: 8),
          Text(
            "如有疑问请联系客服：400-021-1773",
            style: TextStyle(fontSize: 13, color: Colors.green[800]),
          ),
          Row(
            children: [
              Expanded(
                child: FutureBuilder<String>(
                  future: getVersion(),
                  builder: (context, snapshot) {
                    // 判断是否还在加载
                    if (snapshot.connectionState == ConnectionState.waiting) {
                      return const Text("");
                    }

                    // 如果加载完成且有数据
                    if (snapshot.hasData) {
                      return TextX.labelSmall(
                        "当前版本: ${snapshot.data}",
                        color: Colors.green[800],
                      );
                    }

                    // 错误处理
                    return const Text("");
                  },
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildLogoutButton() {
    return ElevatedButton(
      onPressed: () {
        controller.logout();
      },
      style: ElevatedButton.styleFrom(
        backgroundColor: Color.fromRGBO(204, 52, 46, 1),
        foregroundColor: Colors.white,
        minimumSize: const Size(double.infinity, 48),
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(24)),
        elevation: 2,
      ),
      child: const Text(
        '退出登录',
        style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
      ),
    );
  }
}
