import 'package:badges/badges.dart' as badges;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:functional_widget_annotation/functional_widget_annotation.dart';
import 'package:get/get.dart';
import 'package:making_school_asignment_app/common/mixins/getx_keepalive_widget.dart';
import 'package:making_school_asignment_app/common/utils/utils.dart';
import 'package:making_school_asignment_app/page/global_widget/my_text.dart';
import 'package:making_school_asignment_app/routes/app_pages.dart';

import 'home_logic.dart';

part 'home_view.g.dart';

class HomePage extends GetxKeepAliveWidget<HomeLogic> {
  const HomePage({super.key});

  @override
  void initState() {
    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      statusBarColor: Colors.transparent, //状态栏背景颜色
      statusBarIconBrightness: Brightness.light,
      systemStatusBarContrastEnforced: false,
    ));
    super.initState();
  }

  @override
  Widget buildContent(context, controller) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: OrientationBuilder(
        builder: (BuildContext context, Orientation orientation) {
          final state = controller.state;
          return EasyRefresh(
            firstRefresh: false,
            taskIndependence: true,
            enableControlFinishLoad: true,
            controller: controller.refreshController,
            header: MaterialHeader(),
            onRefresh: () async {
              state.pageNumber = 1;
              return controller.getList();
            },
            child: CustomScrollView(
              slivers: [
                // 顶部横幅区域
                SliverAppBar(
                  expandedHeight: 300.h,
                  floating: false,
                  pinned: false,
                  backgroundColor: Colors.transparent,
                  flexibleSpace: FlexibleSpaceBar(
                    background: Image.asset(
                      'assets/images/home_banner.png',
                      width: Get.width,
                      fit: BoxFit.cover,
                    ),
                  ),
                ),
                // 主要内容区域
                SliverToBoxAdapter(
                  child: Container(
                    padding: EdgeInsets.symmetric(vertical: 0, horizontal: 20.r),
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.only(topLeft: Radius.circular(30.r), topRight: Radius.circular(30.r)),
                    ),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        SizedBox(height: 20.r),
                        // 标题区域
                        Row(
                          children: [
                            Icon(
                              Icons.assignment_outlined,
                              size: 24.sp,
                              color: const Color(0xFF4F4F4F),
                            ),
                            SizedBox(width: 8.r),
                            Text(
                              '我的作业管理',
                              style: TextStyle(
                                  fontSize: 22.sp, color: const Color(0xFF2C2C2C), fontWeight: FontWeight.w700),
                            ),
                            const Spacer(),
                            // 刷新按钮
                            IconButton(
                              onPressed: () => controller.refreshController.callRefresh(),
                              icon: Icon(
                                Icons.refresh,
                                size: 20.sp,
                                color: const Color(0xFF4F4F4F),
                              ),
                              tooltip: '刷新数据',
                            )
                          ],
                        ),

                        SizedBox(height: 24.r),
                        // 功能菜单网格
                        _buildMenuGrid(context, state),
                        SizedBox(height: 20.r),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          );
        },
      ),
    );
  }

  Widget _buildStatCard(String title, String value, Color color, IconData icon) {
    return Container(
      padding: EdgeInsets.all(12.r),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8.r),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 4,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        children: [
          Icon(icon, color: color, size: 20.sp),
          SizedBox(height: 4.r),
          Text(
            value,
            style: TextStyle(
              fontSize: 18.sp,
              fontWeight: FontWeight.bold,
              color: color,
            ),
          ),
          Text(
            title,
            style: TextStyle(
              fontSize: 12.sp,
              color: const Color(0xFF6C757D),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildMenuGrid(BuildContext context, dynamic state) {
    return Column(
      children: [
        // 第一行
        Row(
          children: [
            Expanded(
              child: Obx(() => $MenuItem(
                    bgImg: 'assets/images/home_bg_01.png',
                    name: '作业批阅',
                    value: state.totalCount.value > 0 ? state.totalCount.value.toString() : null,
                    url: Routes.readOverPage,
                    isPrimary: true,
                  )),
            ),
            SizedBox(width: 16.r),
            const Expanded(
              child: $MenuItem(
                bgImg: 'assets/images/home_bg_02.png',
                name: '知识点掌握',
                url: Routes.studentHistoryWorkPage,
                page: 'points',
              ),
            ),
          ],
        ),
        SizedBox(height: 16.r),
        // 第二行
        Row(
          children: [
            const Expanded(
              child: $MenuItem(
                bgImg: 'assets/images/home_bg_03.png',
                name: '学生历史作业',
                url: Routes.studentHistoryWorkPage,
                page: 'history',
              ),
            ),
            SizedBox(width: 16.r),
            const Expanded(
              child: $MenuItem(bgImg: 'assets/images/home_bg_04.png', name: '答题轨迹', url: Routes.answerTrajectoryPage),
            ),
          ],
        ),
        SizedBox(height: 16.r),
        // 第三行
        Row(
          children: [
            const Expanded(
              child: $MenuItem(
                bgImg: 'assets/images/home_bg_05.png',
                name: '优先批阅设定',
                url: Routes.studentHistoryWorkPage,
                page: 'set',
              ),
            ),
            SizedBox(width: 16.r),
            // 占位空间
            const Expanded(child: SizedBox()),
          ],
        ),
      ],
    );
  }
}

@swidget
Widget $menuItem({
  required String bgImg,
  required String name,
  String? value,
  required String url,
  String? page,
  bool isPrimary = false,
}) {
  return Material(
    color: Colors.transparent,
    child: InkWell(
      onTap: () {
        Get.toNamed(url, arguments: {'page': page ?? ''});
      },
      borderRadius: BorderRadius.circular(12.r),
      child: Semantics(
        label: '$name${value != null ? '，待处理数量：$value' : ''}',
        hint: '点击进入$name页面',
        button: true,
        child: Container(
          width: (Get.width - 60.r) / 2,
          height: (Get.width - 60.r) / 2 * 86 / 164,
          padding: EdgeInsets.all(16.r),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(12.r),
            gradient: isPrimary
                ? const LinearGradient(
                    begin: Alignment.topLeft,
                    end: Alignment.bottomRight,
                    colors: [
                      Color(0xFF667eea),
                      Color(0xFF764ba2),
                    ],
                  )
                : null,
            color: isPrimary ? null : Colors.white,
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.08),
                blurRadius: 8,
                offset: const Offset(0, 2),
              ),
            ],
            image: !isPrimary
                ? DecorationImage(
                    image: AssetImage(bgImg),
                    fit: BoxFit.cover,
                    colorFilter: ColorFilter.mode(
                      Colors.white.withOpacity(0.8),
                      BlendMode.srcATop,
                    ),
                  )
                : null,
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Expanded(
                    child: Text(
                      name,
                      style: TextStyle(
                        fontSize: 14.sp,
                        color: isPrimary ? Colors.white : const Color(0xFF2C2C2C),
                        fontWeight: FontWeight.w600,
                      ),
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                  if (value != null && value != '')
                    Semantics(
                      label: '待处理数量：$value',
                      child: Container(
                        width: 20.r,
                        height: 20.r,
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                          color: isPrimary ? Colors.white : const Color(0xFFFF6969),
                          borderRadius: BorderRadius.all(Radius.circular(10.r)),
                        ),
                        child: Text(
                          value,
                          style: TextStyle(
                              fontSize: 10.sp,
                              color: isPrimary ? const Color(0xFFFF6969) : Colors.white,
                              fontWeight: FontWeight.w600),
                        ),
                      ),
                    )
                ],
              ),
              const Spacer(),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  if (isPrimary)
                    Icon(
                      Icons.arrow_forward_ios,
                      size: 14.sp,
                      color: Colors.white,
                    )
                  else
                    Image.asset(
                      'assets/images/home_right_icon.png',
                      width: 16.r,
                      height: 16.r,
                      semanticLabel: '进入图标',
                    ),
                ],
              ),
            ],
          ),
        ),
      ),
    ),
  );
}

class EntranceModel extends Object {
  String title;
  String image;
  String navigationUrl;
  String? page;

  EntranceModel({required this.title, required this.image, required this.navigationUrl, this.page});
}

@swidget
Widget $termRow(BuildContext context, List<EntranceModel> items, int? data) {
  var leng = items.length;
  Widget childWidget;
  switch (leng) {
    case 1:
      childWidget = Row(children: [Expanded(child: $TermItem(items[0], data!))]);
      break;
    case 2:
      childWidget = Row(children: [
        Expanded(flex: 9, child: $TermItem(items[0], data!)),
        // const Expanded(flex: 1, child: SizedBox()),
        SizedBox(width: ScreenUtil().screenWidth / 30),
        Expanded(flex: 9, child: $TermItem(items[1], data)),
      ]);
      break;
    case 3:
      double theHeight = ScreenUtil().screenWidth / 30 + 54.h * 2;
      childWidget = Row(
        children: [
          Expanded(child: $TermItem(items[0], data!, theHeight: theHeight)),
          SizedBox(width: ScreenUtil().screenWidth / 30),
          Expanded(
            child: SizedBox(
              height: theHeight,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  $TermItem(items[1], data),
                  $TermItem(items[2], data),
                ],
              ),
            ),
          ),
        ],
      );
      break;
    default:
      childWidget = Container();
  }

  return Container(padding: EdgeInsets.symmetric(horizontal: 14.w), child: childWidget);
}

@swidget
Widget $termItem(BuildContext context, EntranceModel e, int data, {double? theHeight}) {
  bool isJob = e.title == '作业批阅';

  return Material(
    color: Colors.white,
    elevation: 3.r,
    shadowColor: const Color.fromRGBO(231, 231, 231, 1),
    borderRadius: BorderRadius.all(Radius.circular(8.r)),
    child: InkWell(
        onTap: () {
          Get.toNamed(e.navigationUrl, arguments: {'page': e.page ?? ''});
        },

        // splashColor: splashColor,
        borderRadius: BorderRadius.all(Radius.circular(8.r)),
        child: badges.Badge(
          showBadge: isJob && data > 0,
          ignorePointer: false,
          badgeContent: quickText(data, color: Colors.white, size: 10.sp),
          badgeAnimation: const badges.BadgeAnimation.rotation(
            animationDuration: Duration(seconds: 1),
            colorChangeAnimationDuration: Duration(seconds: 1),
            loopAnimation: false,
            curve: Curves.fastOutSlowIn,
            colorChangeAnimationCurve: Curves.easeInCubic,
          ),
          badgeStyle: badges.BadgeStyle(
            badgeColor: const Color.fromRGBO(255, 105, 105, 1),
            shape: badges.BadgeShape.square,
            borderRadius: BorderRadius.only(
                topLeft: Radius.circular(10.r), topRight: Radius.circular(8.5.r), bottomRight: Radius.circular(8.5.r)),
            // borderSide: BorderSide(color: Colors.white, width: 2),
            elevation: 1,
            padding: EdgeInsets.symmetric(horizontal: Utils.isPad() ? 11.w : 16.w, vertical: 2.h),
          ),
          position: badges.BadgePosition.topEnd(top: 10.r, end: 10.r),
          child: Container(
            height: theHeight,
            padding: EdgeInsets.symmetric(vertical: 12.h),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.all(Radius.circular(8.r)),
              // boxShadow: [
              //   BoxShadow(
              //     color: const Color.fromRGBO(231, 231, 231, 1),
              //     offset: Offset(4.w, 6.h), //阴影y轴偏移量
              //     blurRadius: 8, //阴影模糊程度
              //     spreadRadius: 0.2, //阴影扩散程度
              //   )
              // ],
              // border: Border.all(width: 0.5.w, color: Color.fromARGB(255, 219, 226, 250)),
            ),
            alignment: Alignment.center,
            child: isJob
                ? Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Image.asset(e.image, height: 32.r, width: 32.r, fit: BoxFit.cover),
                      SizedBox(height: 6.r),
                      quickText(e.title,
                          size: 12.sp, color: const Color.fromRGBO(79, 79, 79, 1), fontWeight: FontWeight.w500),
                    ],
                  )
                : Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Image.asset(e.image, height: 32.r, width: 32.r, fit: BoxFit.cover),
                      SizedBox(width: 6.r),
                      quickText(e.title,
                          size: 12.sp, color: const Color.fromRGBO(79, 79, 79, 1), fontWeight: FontWeight.w500),
                    ],
                  ),
          ),
        )),
  );
}
