import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:loopin/IM/controller/im_user_info_controller.dart';
import 'package:loopin/components/my_qrcode.dart';
import 'package:loopin/pages/my/merchant/balance/balance.dart';
import 'package:loopin/pages/my/merchant/balance/controller.dart';
import 'package:loopin/utils/index.dart';
import 'package:loopin/utils/scan_code_type.dart';

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

  @override
  State<AllFunctionsPage> createState() => _AllFunctionsPageState();
}

class _AllFunctionsPageState extends State<AllFunctionsPage> {
  // 功能数据列表 - 添加唯一ID
  final List<Map<String, dynamic>> functionList = [
    {
      'title': '主页展示',
      'items': [
        {'id': 'home_order', 'icon': 'assets/images/ico_order.png', 'label': '订单'},
        {'id': 'home_balance', 'icon': 'assets/images/ico_dhx.png', 'label': '余额'},
        {'id': 'home_hym', 'icon': 'assets/images/ico_tgm.png', 'label': '好友码'},
        {'id': 'home_promo', 'icon': 'assets/images/ico_tgm.png', 'label': '推广码'},
      ]
    },
    {
      'title': '更多功能',
      'items': [
        {'id': 'more_seller_order', 'icon': 'assets/images/ico_order.png', 'label': '商家订单'},
        {'id': 'more_seller_income', 'icon': 'assets/images/ico_sh.png', 'label': '商家营收'},
      ]
    },
  ];
  final ImUserInfoController controller = Get.find<ImUserInfoController>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFF0F0F0F),
      appBar: AppBar(
        backgroundColor: const Color(0xFF1A1A1A),
        elevation: 0,
        centerTitle: true,
        title: const Text(
          '全部功能',
          style: TextStyle(
            color: Colors.white,
            fontSize: 14,
            fontWeight: FontWeight.w600,
          ),
        ),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: Colors.white),
          onPressed: () => Navigator.pop(context),
        ),
      ),
      body: Container(
        decoration: const BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [
              Color(0xFF1A1A1A),
              Color(0xFF0F0F0F),
            ],
          ),
        ),
        child: ListView.builder(
          padding: const EdgeInsets.symmetric(vertical: 12),
          itemCount: functionList.length,
          itemBuilder: (context, sectionIndex) {
            final section = functionList[sectionIndex];
            final role = controller.role.value;
            final isSeller = Utils.hasRole(role, 2);
            if (section['title'] == '更多功能' && !isSeller) {
              return SizedBox();
            } else {
              return _buildSection(section);
            }
          },
        ),
      ),
    );
  }

  Widget _buildSection(Map<String, dynamic> section) {
    final role = controller.role.value;
    final isSeller = Utils.hasRole(role, 2);
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.min,
      children: [
        // 分区标题
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
          child: Text(
            section['title'],
            style: const TextStyle(
              fontSize: 12,
              fontWeight: FontWeight.w600,
              color: Colors.white70,
            ),
          ),
        ),

        // 功能项网格
        GridView.builder(
          physics: const NeverScrollableScrollPhysics(),
          shrinkWrap: true,
          padding: const EdgeInsets.symmetric(horizontal: 16),
          gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 4,
            crossAxisSpacing: 12,
            mainAxisSpacing: 16,
            childAspectRatio: 0.85,
          ),
          itemCount: (section['items'] as List).length,
          itemBuilder: (context, index) {
            final item = (section['items'] as List)[index];
            final role = controller.role.value;
            final hasRole = Utils.hasRole(role, 5);
            if (item['id'] == 'home_promo' && !hasRole) {
              return SizedBox();
            } else {
              return _buildFunctionItem(item);
            }
          },
        ),

        // 分隔线 - 只在不是最后一个section时显示
        // if (functionList.indexOf(section) != functionList.length - 1)
        if (isSeller)
          Container(
            height: 2,
            margin: const EdgeInsets.symmetric(vertical: 8, horizontal: 20),
            decoration: BoxDecoration(
              gradient: LinearGradient(
                colors: [
                  Color.fromRGBO(128, 128, 128, 0.3),
                  Color.fromRGBO(158, 158, 158, 0.1),
                  Color.fromRGBO(128, 128, 128, 0.3),
                ],
              ),
            ),
          ),
      ],
    );
  }

  Widget _buildFunctionItem(Map<String, dynamic> item) {
    return GestureDetector(
      onTap: () {
        _handleFunctionTap(item['id']);
      },
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          SizedBox(
            width: 36,
            height: 36,
            child: Center(
              child: Image.asset(
                item['icon'],
                width: 26,
                height: 26,
                color: Colors.white,
              ),
            ),
          ),
          const SizedBox(height: 4),
          // 标签
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 1),
            child: Text(
              item['label'],
              style: const TextStyle(
                fontSize: 11,
                color: Colors.white70,
                fontWeight: FontWeight.w500,
              ),
              textAlign: TextAlign.center,
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            ),
          ),
        ],
      ),
    );
  }

  void _handleFunctionTap(String functionId) {
    switch (functionId) {
      case 'home_order':
        Get.toNamed('/myOrder');
        break;
      case 'home_balance':
        // 钱包
        Get.put(BalanceController());
        Get.to(() => Balance());
        // showLogoutDialog(context);
        break;
      case 'home_hym':
        qrcodeAlertDialog(context);
        break;
      case 'home_promo':
        // 推广码
        qrcodeAlertDialog(context);
        break;
      case 'more_seller_order':
        Get.toNamed('/sellerOrder');
        break;
      case 'more_seller_income':
        Get.toNamed('/merchant/income');
        break;
    }
  }

  // 二维码名片弹窗
  void qrcodeAlertDialog(BuildContext context) {
    final role = controller.role.value;
    final isLeader = Utils.hasRole(role, 5);
    showDialog(
      context: context,
      builder: (context) {
        return UnconstrainedBox(
          constrainedAxis: Axis.vertical,
          child: SizedBox(
            width: 350.0,
            child: AlertDialog(
              contentPadding: const EdgeInsets.symmetric(horizontal: 10.0, vertical: 20.0),
              backgroundColor: Colors.white,
              surfaceTintColor: Colors.white,
              shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15.0)),
              content: Padding(
                padding: const EdgeInsets.symmetric(horizontal: 10.0),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    MyQrcode(
                      prefix: isLeader ? QrTypeCode.tgm : QrTypeCode.hym,
                      text: isLeader ? '团长码' : '',
                    )
                  ],
                ),
              ),
            ),
          ),
        );
      },
    );
  }

  // 退出登录弹窗
  void showLogoutDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          content: const Text('确认退出当前账号吗？', style: TextStyle(fontSize: 16.0)),
          backgroundColor: Colors.white,
          surfaceTintColor: Colors.white,
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15.0)),
          elevation: 2.0,
          actionsPadding: const EdgeInsets.all(15.0),
          actions: [
            TextButton(
              onPressed: () {
                Get.back();
              },
              child: const Text('取消', style: TextStyle(color: Colors.black54)),
            ),
            TextButton(onPressed: () => {}, child: const Text('退出登录', style: TextStyle(color: Colors.red))),
          ],
        );
      },
    );
  }
}
