import 'package:flutter/foundation.dart';
import 'package:flutter/material.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/job/marking_models/do_paper_details_param.dart';
import 'package:making_school_asignment_app/common/job/marking_models/do_paper_details_result.dart';
import 'package:making_school_asignment_app/common/utils/anti_shake_throttling.dart';
import 'package:making_school_asignment_app/common/utils/toast_utils.dart';
import 'package:making_school_asignment_app/page/global_widget/my_text.dart';
import 'package:making_school_asignment_app/page/home_page/children/homework_review/configuration_files/index.dart';
import 'package:making_school_asignment_app/routes/app_pages.dart';

import 'original_manuscript_handwriting/answer_handwriting_view.dart';

part 'dropdown_switch_students_type.g.dart';

// 常量定义
class _Constants {
  static const double containerHeight = 30.0;
  static const double borderRadius = 4.0;
  static const double iconSize = 12.0;
  static const double textSize = 14.0;
  static const double smallTextSize = 12.0;
  static const double tinyTextSize = 4.0;

  // 颜色常量
  static const Color shadowColor = Color.fromRGBO(46, 91, 255, 0.2);
  static const Color backgroundColor = Color.fromRGBO(244, 244, 244, 1);
  static const Color textColor = Color.fromRGBO(79, 79, 79, 1);
  static const Color iconColor = Color.fromRGBO(104, 103, 103, 1);
  static const Color priorityIconDisabledColor = Color.fromRGBO(164, 164, 164, 1);

  // 间距常量
  static const double paddingSmall = 2.0;
  static const double paddingMedium = 8.0;
  static const double paddingLarge = 12.0;
  static const double paddingXL = 13.0;

  // 阴影参数
  static const double shadowBlurRadius = 14.0;
  static const double shadowSpreadRadius = 0.5;
  static const Offset shadowOffset = Offset(2.0, 2.0);
}

/// 学生和页码切换组件
///
/// 提供作业批阅时的页码选择和学生选择功能，包含：
/// - 页码下拉选择框
/// - 学生下拉选择框
/// - 继续批阅按钮
/// - 学生历史作业按钮
/// - 学生笔迹查看按钮

class DropdownSwitchStudentsType extends StatelessWidget {
  const DropdownSwitchStudentsType({super.key});

  @override
  Widget build(BuildContext context) {
    final logic = Get.find<HomeworkReviewLogic>();
    final stateData = logic.state.data;

    return Container(
      height: _Constants.containerHeight.h,
      padding: EdgeInsets.only(
          bottom: _Constants.paddingSmall.r, left: _Constants.paddingLarge.r, right: _Constants.paddingLarge.r),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: _Constants.shadowColor,
            offset: Offset(_Constants.shadowOffset.dx.w, _Constants.shadowOffset.dy.h),
            blurRadius: _Constants.shadowBlurRadius,
            spreadRadius: _Constants.shadowSpreadRadius,
          )
        ],
      ),
      child: Row(
        children: [
          Expanded(
            flex: 2,
            child: _buildPageDropdown(logic, stateData),
          ),
          SizedBox(width: _Constants.paddingMedium.w),
          Expanded(
            flex: 3,
            child: _buildStudentDropdown(context, logic, stateData),
          ),
          SizedBox(width: _Constants.paddingMedium.w),
          const Expanded(
            flex: 6,
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                $ContinueToReview(), // 继续批阅
                $HistoryHomework(), // 学生历史作业
                $StudentHandwriting(), // 学生笔迹
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 构建页码下拉框
  Widget _buildPageDropdown(HomeworkReviewLogic logic, Rx<DoPaperDetailsResult?> stateData) {
    return Container(
      padding: EdgeInsets.only(left: 10.w),
      decoration: BoxDecoration(
        color: _Constants.backgroundColor,
        borderRadius: BorderRadius.circular(_Constants.borderRadius.r),
      ),
      child: Obx(() {
        final data = stateData.value;
        return DropdownButton(
          isExpanded: true,
          underline: Container(),
          padding: EdgeInsets.only(right: 4.w),
          icon: const Icon(Icons.keyboard_arrow_down_rounded),
          value: data?.templateId,
          hint: const Text('请选择作业页码'),
          items: data?.templateIdKeys?.map((e) {
            return DropdownMenuItem(
              value: e,
              child: quickText(
                '${data.templateIdKeyMap![e]}页',
                color: _Constants.textColor,
                size: _Constants.textSize.sp,
              ),
            );
          }).toList(),
          onChanged: (value) => _handlePageChange(logic, value),
        );
      }),
    );
  }

  /// 构建学生下拉框
  Widget _buildStudentDropdown(BuildContext context, HomeworkReviewLogic logic, Rx<DoPaperDetailsResult?> stateData) {
    return Container(
      padding: EdgeInsets.only(left: _Constants.paddingXL.w),
      decoration: BoxDecoration(
        color: _Constants.backgroundColor,
        borderRadius: BorderRadius.circular(_Constants.borderRadius.r),
      ),
      child: Obx(() {
        final data = stateData.value;
        return DropdownButton(
          padding: EdgeInsets.only(right: 4.w),
          icon: const Icon(Icons.keyboard_arrow_down_rounded),
          value: data?.studentId,
          underline: Container(),
          isExpanded: true,
          items: data?.students.map((student) {
            return DropdownMenuItem(
              value: student.id,
              child: _buildStudentItem(context, student),
            );
          }).toList(),
          hint: const Text('请选择学生'),
          onChanged: (value) => _handleStudentChange(logic, value),
        );
      }),
    );
  }

  /// 构建学生项目
  Widget _buildStudentItem(BuildContext context, PaperStudents student) {
    return Stack(
      alignment: const FractionalOffset(0, 0.5),
      children: [
        Container(
          padding: EdgeInsets.only(left: 16.w),
          child: quickText(
            student.name,
            size: _Constants.textSize.sp,
            color: _Constants.textColor,
          ),
        ),
        Stack(
          alignment: const FractionalOffset(0.52, 0.26),
          children: [
            Icon(
              const IconData(0xe63d, fontFamily: "AlibabaIcon"),
              size: _Constants.iconSize.sp,
              color: student.isPriority ? Theme.of(context).primaryColor : _Constants.priorityIconDisabledColor,
            ),
            quickText('优先', size: _Constants.tinyTextSize.sp, color: Colors.white),
          ],
        ),
      ],
    );
  }

  /// 处理页码变更
  void _handlePageChange(HomeworkReviewLogic logic, dynamic value) {
    if (logic.state.param.value.templateId == value) return;

    final templateIds = logic.state.data.value?.templateIds;
    if (value == null || templateIds == null) return;

    final templateIdKeyMap = logic.state.data.value?.templateIdKeyMap;
    final answeredAlready = templateIds[value.toString()];

    if (answeredAlready != null && !answeredAlready) {
      _showUnansweredPageToast(logic.state.data.value, value, templateIdKeyMap);
      return;
    }

    logic.state.param.value.templateId = value;
    logic.state.param.value = DoPaperDetailsParam.fromJson(logic.state.param.value.toJson());
  }

  /// 处理学生变更
  void _handleStudentChange(HomeworkReviewLogic logic, dynamic value) {
    if (logic.state.param.value.studentId == value) return;

    logic.state.param.value.studentId = value;
    logic.state.param.value = DoPaperDetailsParam.fromJson(logic.state.param.value.toJson());
  }

  /// 显示未作答页面提示
  void _showUnansweredPageToast(DoPaperDetailsResult? data, dynamic value, Map<dynamic, dynamic>? templateIdKeyMap) {
    final currentStudentId = data?.studentId;
    final students = data?.students ?? [];

    // 获取当前学生姓名
    PaperStudents? currentStudent;
    if (currentStudentId != null) {
      try {
        currentStudent = students.firstWhere((e) => e.id == currentStudentId);
      } catch (e) {
        currentStudent = null;
      }
    }

    final studentName = currentStudent?.name ?? '当前学生';
    final questionNumber = templateIdKeyMap?[value] ?? '当前选择页';

    ToastUtils.showInfo("$studentName第$questionNumber页，未作答 无需批阅");
  }
}

@swidget
Widget $studentHandwriting(BuildContext context) {
  final logic = Get.find<HomeworkReviewLogic>();
  final stateData = logic.state.data;

  return InkWell(
    onTap: () => easyThrottle(
      'SHOW_ANSWER_HANDWRITING',
      () async {
        final data = stateData.value;
        final studentId = data?.studentId;
        if (studentId == null) return;

        final homeworkId = logic.state.param.value.homeworkId;
        final templateId = data?.templateId;
        final templateIdKeyMap = data?.templateIdKeyMap;

        int? pageNum;
        if (templateIdKeyMap != null && templateId != null) {
          pageNum = templateIdKeyMap[templateId];
        }

        await showAnswerHandwriting(
          context,
          homeworkId: homeworkId,
          studentId: studentId,
          templateId: templateId,
          pageNum: pageNum,
        );
        ToastUtils.dismiss();
      },
    ),
    child: Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Icon(
          Icons.edit_outlined,
          size: _Constants.iconSize.sp,
          color: Theme.of(context).primaryColor.withOpacity(0.8),
        ),
        SizedBox(width: 1.w),
        quickText(
          '学生笔迹',
          size: _Constants.smallTextSize.sp,
          decoration: TextDecoration.underline,
          color: Theme.of(context).primaryColor.withOpacity(0.9),
        ),
      ],
    ),
  );
}

@swidget
Widget $continueToReview(BuildContext context, {bool isFloatingAction = false}) {
  final logic = Get.find<HomeworkReviewLogic>();
  final stateData = logic.state.data;

  return Obx(() {
    final data = stateData.value;

    // 检查是否需要显示继续批阅按钮
    if (!_shouldShowContinueReview(data)) {
      return const SizedBox();
    }

    void onPressed() => easyThrottle(
          'DO_PAPERS_JOB_CONTINUE_TO_REVIEW',
          () {
            final param = logic.state.param.value;
            param.templateId = null;
            param.studentId = null;
            logic.state.param.value = DoPaperDetailsParam.fromJson(param.toJson());
          },
        );

    if (isFloatingAction) {
      return FloatingActionButton(
        elevation: 8,
        tooltip: "继续批阅",
        backgroundColor: Colors.white,
        onPressed: onPressed,
        child: Icon(
          Icons.flip_camera_android_outlined,
          size: 20.sp,
          color: Theme.of(context).primaryColor,
        ),
      );
    }

    return InkWell(
      onTap: onPressed,
      child: Row(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Icon(
            Icons.flip_camera_android_outlined,
            size: _Constants.iconSize.sp,
            color: Theme.of(context).primaryColor.withOpacity(0.8),
          ),
          SizedBox(width: 1.w),
          quickText(
            '继续批阅',
            size: _Constants.smallTextSize.sp,
            decoration: TextDecoration.underline,
            color: Theme.of(context).primaryColor.withOpacity(0.9),
          ),
          SizedBox(width: 2.w),
        ],
      ),
    );
  });
}

/// 检查是否应该显示继续批阅按钮
bool _shouldShowContinueReview(DoPaperDetailsResult? data) {
  if (data == null) return false;

  if (data.needAnnotate) {
    return data.continuePage == null || data.continuePage!.templateId != data.templateId;
  } else {
    return data.totalUnAnnotateCount > 0;
  }
}

/// 学生历史作业
@swidget
Widget $historyHomework(BuildContext context) {
  final logic = Get.find<HomeworkReviewLogic>();
  final stateData = logic.state.data;

  return InkWell(
    onTap: () => easyThrottle(
      'DO_PAPERS_JOB_HISTORICAL_HOMEWORK',
      () => _navigateToStudentHistory(logic, stateData.value),
    ),
    child: Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      mainAxisSize: MainAxisSize.min,
      children: [
        Icon(
          Icons.location_history,
          size: _Constants.iconSize.sp,
          color: _Constants.iconColor,
        ),
        SizedBox(width: 1.w),
        quickText(
          '历史作业',
          size: _Constants.smallTextSize.sp,
          decoration: TextDecoration.underline,
          color: Theme.of(context).primaryColor.withOpacity(0.8),
        ),
      ],
    ),
  );
}

/// 导航到学生历史作业页面
void _navigateToStudentHistory(HomeworkReviewLogic logic, DoPaperDetailsResult? data) {
  final studentId = data?.studentId;
  final students = data?.students ?? [];

  if (kDebugMode) print('Student ID: $studentId');

  if (studentId == null || students.isEmpty) return;

  PaperStudents? currentStudent;
  try {
    currentStudent = students.firstWhere((e) => e.id == studentId);
  } catch (e) {
    if (kDebugMode) print('Student not found: $e');
    return;
  }

  Get.toNamed(Routes.studentWorkDetailPage, arguments: {
    'studentId': studentId,
    'studentName': currentStudent.name,
    'subject': logic.state.param.value.subject,
  });
}
