import 'dart:async';
import 'dart:ui';

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 'package:making_school_asignment_app/common/utils/utils.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),
    )..addListener(toUp);

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

    super.initState();
  }

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

    eventCancel();
    super.dispose();
  }

  void toUp() => toUpState(setState, () {}, mounted);

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      left: false,
      right: false,
      top: false,
      child: ClipRRect(
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(25.r),
          topRight: Radius.circular(25.r),
        ),
        child: BackdropFilter(
          filter: ImageFilter.blur(sigmaX: 25, sigmaY: 25),
          child: Container(
            width: double.infinity,
            height: _animationController.value * 70.h,
            decoration: BoxDecoration(
              // 增强的液态玻璃背景
              gradient: LinearGradient(
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
                colors: [
                  Colors.white.withOpacity(0.12),
                  Colors.white.withOpacity(0.08),
                  Colors.white.withOpacity(0.06),
                  Colors.black.withOpacity(0.03),
                ],
                stops: const [0.0, 0.3, 0.7, 1.0],
              ),
              // 圆润的液态边缘
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(25.r),
                topRight: Radius.circular(25.r),
              ),
              // 多层阴影增强液态质感
              boxShadow: [
                // 主阴影 - 深度感
                BoxShadow(
                  color: Colors.black.withOpacity(0.25),
                  blurRadius: 30,
                  offset: const Offset(0, -8),
                  spreadRadius: -10,
                ),
                // 内部高光 - 玻璃反射
                BoxShadow(
                  color: Colors.white.withOpacity(0.15),
                  blurRadius: 3,
                  offset: const Offset(0, 2),
                ),
                // 彩色光晕 - 液态折射
                BoxShadow(
                  color: Colors.blue.withOpacity(0.05),
                  blurRadius: 20,
                  offset: const Offset(0, -3),
                  spreadRadius: -5,
                ),
              ],
            ),
            child: Stack(
              children: [
                // 增强的液态边缘装饰层
                Positioned(
                  top: 0,
                  left: 0,
                  right: 0,
                  height: 5.h,
                  child: Container(
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(25.r),
                        topRight: Radius.circular(25.r),
                      ),
                      gradient: LinearGradient(
                        begin: Alignment.topCenter,
                        end: Alignment.bottomCenter,
                        colors: [
                          Colors.white.withOpacity(0.25),
                          Colors.white.withOpacity(0.12),
                          Colors.white.withOpacity(0.05),
                          Colors.transparent,
                        ],
                        stops: const [0.0, 0.3, 0.6, 1.0],
                      ),
                    ),
                  ),
                ),
                // 液态波纹效果
                Positioned.fill(
                  child: Container(
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(25.r),
                        topRight: Radius.circular(25.r),
                      ),
                      gradient: RadialGradient(
                        center: const Alignment(0.0, -0.8),
                        radius: 1.5,
                        colors: [
                          Colors.white.withOpacity(0.08),
                          Colors.white.withOpacity(0.04),
                          Colors.transparent,
                          Colors.white.withOpacity(0.02),
                          Colors.transparent,
                        ],
                        stops: const [0.0, 0.2, 0.4, 0.7, 1.0],
                      ),
                    ),
                  ),
                ),
                // 液态流动光效
                Positioned.fill(
                  child: Container(
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(25.r),
                        topRight: Radius.circular(25.r),
                      ),
                      gradient: LinearGradient(
                        begin: const Alignment(-1.0, -1.0),
                        end: const Alignment(1.0, 1.0),
                        colors: [
                          Colors.transparent,
                          Colors.white.withOpacity(0.06),
                          Colors.transparent,
                          Colors.white.withOpacity(0.03),
                          Colors.transparent,
                        ],
                        stops: const [0.0, 0.25, 0.5, 0.75, 1.0],
                      ),
                    ),
                  ),
                ),
                // 顶部液滴效果
                Positioned(
                  top: -2,
                  left: 0,
                  right: 0,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: [
                      _buildLiquidDroplet(width: 60.w, height: 4.h),
                      _buildLiquidDroplet(width: 40.w, height: 3.h),
                      _buildLiquidDroplet(width: 50.w, height: 3.5.h),
                    ],
                  ),
                ),
                // 主要内容
                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,
                                  ),
                                ),
                                _buildGlassDivider(),
                                // 注解笔
                                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: '注解笔',
                                      )),
                                ),
                                _buildGlassDivider(),
                                // 滑动试题
                                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: '滑动试题',
                                      )),
                                ),
                              ],
                            ),
                          ),
                          _buildHorizontalGlassDivider(),
                          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,
                                  ),
                                ),
                                _buildGlassDivider(),
                                // 撤销上一步
                                Expanded(
                                  child: _buildIconButton(
                                    const IconData(0xe638, fontFamily: "AlibabaIcon"),
                                    () => easyThrottle(
                                      'homework_bottom_action_bar_annotations',
                                      () => eventFire(model: BottomOperationBar(revokeAll: false, revokePreStep: true)),
                                    ),
                                    tooltip: '撤销上一步',
                                  ),
                                ),
                                _buildGlassDivider(),
                                // 全部撤销
                                Expanded(
                                  child: _buildIconButton(
                                    const IconData(0xe637, fontFamily: "AlibabaIcon"),
                                    () => easyThrottle(
                                      'homework_bottom_action_bar_annotations',
                                      () => eventFire(model: BottomOperationBar(revokeAll: true, revokePreStep: false)),
                                    ),
                                    tooltip: '全部撤销',
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                    _buildGlassDivider(),
                    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,
                            ),
                          ),
                          _buildGlassDivider(),
                          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,
                              );
                            }),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  // 液滴效果
  Widget _buildLiquidDroplet({required double width, required double height}) {
    return Container(
      width: width,
      height: height,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.only(
          bottomLeft: Radius.circular(width / 2),
          bottomRight: Radius.circular(width / 2),
        ),
        gradient: LinearGradient(
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          colors: [
            Colors.white.withOpacity(0.3),
            Colors.white.withOpacity(0.15),
            Colors.white.withOpacity(0.05),
            Colors.transparent,
          ],
          stops: const [0.0, 0.3, 0.7, 1.0],
        ),
        boxShadow: [
          BoxShadow(
            color: Colors.white.withOpacity(0.2),
            blurRadius: 4,
            offset: const Offset(0, 1),
          ),
        ],
      ),
    );
  }

  // 增强的垂直玻璃分隔线
  Widget _buildGlassDivider() {
    return Container(
      width: 1.w,
      height: double.infinity,
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          colors: [
            Colors.white.withOpacity(0.05),
            Colors.white.withOpacity(0.15),
            Colors.white.withOpacity(0.25),
            Colors.white.withOpacity(0.15),
            Colors.white.withOpacity(0.05),
          ],
          stops: const [0.0, 0.2, 0.5, 0.8, 1.0],
        ),
        boxShadow: [
          BoxShadow(
            color: Colors.white.withOpacity(0.1),
            blurRadius: 2,
            spreadRadius: 0.5,
          ),
        ],
      ),
    );
  }

  // 增强的水平玻璃分隔线
  Widget _buildHorizontalGlassDivider() {
    return Container(
      width: double.infinity,
      height: 1.h,
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.centerLeft,
          end: Alignment.centerRight,
          colors: [
            Colors.white.withOpacity(0.03),
            Colors.white.withOpacity(0.08),
            Colors.white.withOpacity(0.2),
            Colors.white.withOpacity(0.08),
            Colors.white.withOpacity(0.03),
          ],
          stops: const [0.0, 0.2, 0.5, 0.8, 1.0],
        ),
        boxShadow: [
          BoxShadow(
            color: Colors.white.withOpacity(0.15),
            blurRadius: 3,
            spreadRadius: 0.5,
          ),
        ],
      ),
    );
  }

  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,
        borderRadius: BorderRadius.circular(8.r),
        splashColor: isPrimary ? Colors.white.withOpacity(0.2) : primaryColor.withOpacity(0.2),
        highlightColor: isPrimary ? Colors.white.withOpacity(0.1) : primaryColor.withOpacity(0.1),
        child: Semantics(
          label: text,
          hint: isLoading ? '正在处理中' : (isEnabled ? '点击执行$text操作' : '$text按钮已禁用'),
          button: true,
          enabled: isEnabled && !isLoading,
          child: Container(
            width: double.infinity,
            height: double.infinity,
            decoration: BoxDecoration(
              // 液态玻璃背景
              gradient: isPrimary
                  ? LinearGradient(
                      begin: Alignment.topLeft,
                      end: Alignment.bottomRight,
                      colors: isEnabled
                          ? [
                              primaryColor.withOpacity(0.8),
                              primaryColor.withOpacity(0.6),
                            ]
                          : [
                              primaryColor.withOpacity(0.3),
                              primaryColor.withOpacity(0.2),
                            ],
                    )
                  : LinearGradient(
                      begin: Alignment.topLeft,
                      end: Alignment.bottomRight,
                      colors: [
                        Colors.white.withOpacity(0.08),
                        Colors.white.withOpacity(0.03),
                      ],
                    ),
              borderRadius: BorderRadius.circular(8.r),
              // 液态玻璃边框
              border: Border.all(
                color: isPrimary ? Colors.white.withOpacity(0.2) : Colors.white.withOpacity(0.1),
                width: 0.5,
              ),
            ),
            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,
        borderRadius: BorderRadius.circular(8.r),
        splashColor: primaryColor.withOpacity(0.2),
        highlightColor: primaryColor.withOpacity(0.1),
        child: Tooltip(
          message: tooltip ?? '',
          child: Container(
            width: double.infinity,
            height: double.infinity,
            decoration: BoxDecoration(
              // 液态玻璃背景
              gradient: isActive
                  ? LinearGradient(
                      begin: Alignment.topLeft,
                      end: Alignment.bottomRight,
                      colors: [
                        primaryColor.withOpacity(0.15),
                        primaryColor.withOpacity(0.08),
                      ],
                    )
                  : LinearGradient(
                      begin: Alignment.topLeft,
                      end: Alignment.bottomRight,
                      colors: [
                        Colors.white.withOpacity(0.05),
                        Colors.white.withOpacity(0.02),
                      ],
                    ),
              borderRadius: BorderRadius.circular(8.r),
              // 液态玻璃边框
              border: Border.all(
                color: isActive ? primaryColor.withOpacity(0.3) : Colors.white.withOpacity(0.08),
                width: 0.5,
              ),
            ),
            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,
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
