import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:making_school_asignment_app/common/job/marking_models/do_paper_bus.dart';
import 'package:making_school_asignment_app/common/mixins/event_bus_mixin.dart';
import 'package:making_school_asignment_app/common/utils/anti_shake_throttling.dart';

import '../configuration_files/index.dart';

// 底部操作栏
class BottomAnnotationSwitch extends StatefulWidget {
  const BottomAnnotationSwitch({super.key});

  @override
  State<BottomAnnotationSwitch> createState() => _BottomAnnotationSwitchJobState();
}

class _BottomAnnotationSwitchJobState extends State<BottomAnnotationSwitch>
    with SingleTickerProviderStateMixin, EventBusMixin<BottomOperationBar> {
  late AnimationController _animationController; // 动画
  final _homeworkLogic = Get.find<HomeworkReviewLogic>();
  final _logicControl = Get.find<HomeworkReviewLogic>().annotationState;
  StreamSubscription? _opControllisten;

  @override
  void initState() {
    _animationController = AnimationController(
      vsync: this,
      value: 1, // 设置默认值
      lowerBound: 0,
      upperBound: 1,
      duration: const Duration(milliseconds: 300),
    );

    _opControllisten = _logicControl.opControl.listen((e) {
      if (e) {
        _animationController.forward();
      } else {
        _animationController.reverse();
      }
    });

    super.initState();
  }

  @override
  void dispose() {
    _animationController.dispose();
    _opControllisten?.cancel();

    eventCancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final Widget barContent = Row(
      children: [
        Expanded(
          flex: 7,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Expanded(
                child: Row(
                  children: [
                    // 全对按钮
                    Expanded(
                      child: _buildActionButton(
                        '全对',
                        Icons.check_circle_outline,
                        () => easyThrottle(
                            'homework_bottom_operation_bar_scoring_related', () => _homeworkLogic.allPairs(context)),
                        isEnabled: !_homeworkLogic.state.submitLoading.value,
                        isPrimary: true,
                      ),
                    ),
                    Container(width: 0.5.w, height: double.infinity, color: Colors.white.withOpacity(0.3)),
                    // 注解笔
                    Expanded(
                      child: Obx(() => _buildIconButton(
                            const IconData(0xe635, fontFamily: "AlibabaIcon"),
                            () => easyThrottle('homework_bottom_action_bar_annotations', () {
                              // 互斥：启用注解笔，禁用滑动
                              _logicControl.gestureMove.value = false;
                              _logicControl.pen.value = true;
                            }),
                            isActive: _logicControl.pen.value,
                            tooltip: '注解笔',
                          )),
                    ),
                    Container(width: 0.5.w, height: double.infinity, color: Colors.white.withOpacity(0.3)),
                    // 滑动试题
                    Expanded(
                      child: Obx(() => _buildIconButton(
                            const IconData(0xe636, fontFamily: "AlibabaIcon"),
                            () => easyThrottle('homework_bottom_action_bar_annotations', () {
                              // 互斥：启用滑动，禁用注解笔
                              _logicControl.pen.value = false;
                              _logicControl.gestureMove.value = true;
                            }),
                            isActive: _logicControl.gestureMove.value,
                            tooltip: '滑动试题',
                          )),
                    ),
                  ],
                ),
              ),
              Container(width: double.infinity, color: Colors.white.withOpacity(0.3), height: 0.5.h),
              Expanded(
                child: Row(
                  children: [
                    // 全错按钮
                    Expanded(
                      child: _buildActionButton(
                        '全错',
                        Icons.cancel_outlined,
                        () => easyThrottle('homework_bottom_operation_bar_scoring_related',
                            () => _homeworkLogic.allWrongRating(context)),
                        isEnabled: !_homeworkLogic.state.submitLoading.value,
                        isPrimary: false,
                      ),
                    ),
                    Container(width: 0.5.w, height: double.infinity, color: Colors.white.withOpacity(0.3)),
                    // 撤销上一步
                    Expanded(
                      child: _buildIconButton(
                        const IconData(0xe638, fontFamily: "AlibabaIcon"),
                        () => easyThrottle(
                          'homework_bottom_action_bar_annotations',
                          () => eventFire(model: BottomOperationBar(revokeAll: false, revokePreStep: true)),
                        ),
                        tooltip: '撤销上一步',
                      ),
                    ),
                    Container(width: 0.5.w, height: double.infinity, color: Colors.white.withOpacity(0.3)),
                    // 全部撤销
                    Expanded(
                      child: _buildIconButton(
                        const IconData(0xe637, fontFamily: "AlibabaIcon"),
                        () => easyThrottle(
                          'homework_bottom_action_bar_annotations',
                          () => eventFire(model: BottomOperationBar(revokeAll: true, revokePreStep: false)),
                        ),
                        tooltip: '全部撤销',
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
        Container(width: 0.5.w, height: double.infinity, color: Colors.white.withOpacity(0.3)),
        Expanded(
          flex: 3,
          child: Row(
            children: [
              Expanded(
                child: _buildActionButton(
                  '取消',
                  Icons.clear,
                  () => easyThrottle(
                      'homework_bottom_operation_bar_scoring_related', () => _homeworkLogic.cancelAllRatings()),
                  isEnabled: true,
                  isPrimary: false,
                  isSecondary: true,
                ),
              ),
              Container(width: 0.5.w, height: double.infinity, color: Colors.white.withOpacity(0.3)),
              Expanded(
                child: Obx(() {
                  final submitLoading = _homeworkLogic.state.submitLoading.value;
                  return _buildActionButton(
                    '提交',
                    Icons.send,
                    () => easyThrottle(
                        'homework_bottom_operation_bar_scoring_related', () => _homeworkLogic.submit(context)),
                    isEnabled: !submitLoading,
                    isPrimary: true,
                    isLoading: submitLoading,
                  );
                }),
              ),
            ],
          ),
        ),
      ],
    );

    return SafeArea(
      left: false,
      right: false,
      top: false,
      child: AnimatedBuilder(
        animation: _animationController,
        builder: (context, _) {
          return Container(
            width: double.infinity,
            height: _animationController.value * 70.h,
            decoration: BoxDecoration(
              color: const Color.fromRGBO(83, 83, 83, 1),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.1),
                  blurRadius: 8,
                  offset: const Offset(0, -2),
                ),
              ],
            ),
            child: barContent,
          );
        },
      ),
    );
  }

  Widget _buildActionButton(
    String text,
    IconData icon,
    VoidCallback? onPressed, {
    required bool isEnabled,
    required bool isPrimary,
    bool isSecondary = false,
    bool isLoading = false,
  }) {
    final primaryColor = Theme.of(context).primaryColor;
    const defaultColor = Color.fromRGBO(132, 146, 163, 1);

    return Material(
      color: Colors.transparent,
      child: InkWell(
        onTap: isEnabled ? onPressed : null,
        child: Semantics(
          label: text,
          hint: isLoading ? '正在处理中' : (isEnabled ? '点击执行$text操作' : '$text按钮已禁用'),
          button: true,
          enabled: isEnabled && !isLoading,
          child: Container(
            width: double.infinity,
            height: double.infinity,
            decoration: BoxDecoration(
              color: isPrimary
                  ? (isEnabled ? primaryColor : primaryColor.withOpacity(0.5))
                  : isSecondary
                      ? Colors.transparent
                      : Colors.transparent,
              borderRadius: BorderRadius.circular(4.r),
            ),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                if (isLoading)
                  SizedBox(
                    width: 16.w,
                    height: 16.w,
                    child: CircularProgressIndicator(
                      strokeWidth: 2,
                      valueColor: AlwaysStoppedAnimation<Color>(
                        isPrimary ? Colors.white : primaryColor,
                      ),
                    ),
                  )
                else
                  Icon(
                    icon,
                    size: 16.sp,
                    color: isEnabled
                        ? (isPrimary ? Colors.white : (isSecondary ? Colors.white70 : defaultColor))
                        : Colors.white38,
                  ),
                SizedBox(height: 2.h),
                Text(
                  text,
                  style: TextStyle(
                    fontSize: 10.sp,
                    color: isEnabled
                        ? (isPrimary ? Colors.white : (isSecondary ? Colors.white70 : Colors.white))
                        : Colors.white38,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildIconButton(
    IconData icon,
    VoidCallback? onPressed, {
    bool isActive = false,
    String? tooltip,
  }) {
    final primaryColor = Theme.of(context).primaryColor;
    const defaultColor = Color.fromRGBO(132, 146, 163, 1);

    return Material(
      color: Colors.transparent,
      child: InkWell(
        onTap: onPressed,
        child: Tooltip(
          message: tooltip ?? '',
          child: Container(
            width: double.infinity,
            height: double.infinity,
            decoration: BoxDecoration(
              color: isActive ? primaryColor.withOpacity(0.2) : Colors.transparent,
              borderRadius: BorderRadius.circular(4.r),
            ),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(
                  icon,
                  size: 18.sp,
                  color: isActive ? primaryColor : defaultColor,
                ),
                SizedBox(height: 2.h),
                Container(
                  width: 4.w,
                  height: 4.w,
                  decoration: BoxDecoration(
                    color: isActive ? primaryColor : Colors.transparent,
                    shape: BoxShape.circle,
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
