import 'dart:async';
import 'package:fis_i18n/i18n.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_ui/interface/interactive_container.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flyinsono/architecture/utils/advance_debounce.dart';
import 'package:flyinsono/architecture/utils/prompt_box.dart';

/// 录制按钮
class RecordButton extends FStatefulWidget implements FInteractiveContainer {
  RecordButton({
    required this.onTap,
    required this.onStartRecord,
    required this.onStopRecord,
    required this.buttonGroupWidth,
  });

  @override
  FState<FStatefulWidget> createState() {
    return _RecordButtonState();
  }

  /// 录制一帧
  final Function onTap;

  /// 开始录制
  final Function onStartRecord;

  /// 结束录制
  final Function onStopRecord;

  /// 按钮组宽度
  final double buttonGroupWidth;

  @override
  String get pageName => "RecordButton";
}

class _RecordButtonState extends FState<RecordButton> {
  String title = i18nBook.realTimeConsultation.captureVid.t;
  static const Color _buttonTextColor = Color.fromARGB(255, 199, 198, 201);

  int get baseFontSize => i18nBook.isCurrentChinese ? 16 : 12;

  BoxDecoration get _buttonDecoration => BoxDecoration(
      borderRadius: BorderRadius.all(
        Radius.circular(widget.buttonGroupWidth / 2),
      ),
      border: Border.all(width: 1.5, color: Color.fromARGB(255, 170, 170, 170)),
      color: Color.fromARGB(255, 14, 16, 17));

  ///屏幕缩放比例
  double get devicePixelRatio => MediaQuery.of(context).devicePixelRatio;

  /// 录制开始时间
  DateTime? startTime;

  /// 最大录制时长 s
  static const int maxRecordTime = 30;

  /// 录制剩余时间百分比
  double recordCountDown = 0;

  /// 是否正在录制
  bool isRecording = false;

  /// 录制计时器
  Timer? recordTimer;

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    recordTimer?.cancel();
    recordTimer = null;
    super.dispose();
  }

  @override
  FWidget build(BuildContext context) {
    return FTextTooltip(
      position: i18nBook.isCurrentRussian
          ? DisplayPosition.left
          : DisplayPosition.right,
      textStyle: TextStyle(
        fontSize: 16,
        color: Colors.white,
      ),
      height: isRecording ? 0 : 36,
      decoration: BoxDecoration(
        color: Colors.black.withOpacity(0.8),
        borderRadius: BorderRadius.circular(4),
      ),
      message:
          isRecording ? "" : i18nBook.realTimeConsultation.longPressToRecord.t,
      child: FMouseRegion(
        cursor: SystemMouseCursors.click,
        child: FGestureDetector(
          name: "RecordButton",
          businessParent: this.widget,
          onTap: () {
            advanceDebounce(captureOneFrame, "capture", 1000);
          },
          onLongPressStart: (details) {
            advanceDebounce(startRecord, "capture", 1000);
          },
          onLongPressEnd: (details) {
            /// 结束录制调用需要设置下次的开始延时，但是不需要防抖，所以设置为 0
            advanceDebounce(stopRecord, "capture", 0);
          },
          child: FContainer(
            width: widget.buttonGroupWidth,
            height: widget.buttonGroupWidth,
            margin: EdgeInsets.only(bottom: 10),
            decoration: _buttonDecoration,
            child: FStack(
              children: [
                FCenter(
                  child: FText(
                    title,
                    style: TextStyle(
                      color: _buttonTextColor,
                      fontSize: devicePixelRatio > 1
                          ? baseFontSize / devicePixelRatio
                          : baseFontSize.toDouble(),
                    ),
                  ),
                ),
                if (isRecording)
                  FCenter(
                    child: FContainer(
                      width: widget.buttonGroupWidth - 5,
                      height: widget.buttonGroupWidth - 5,
                      child: FCircularProgressIndicator(
                        strokeWidth: 6,
                        valueColor: AlwaysStoppedAnimation<Color>(Colors.blue),
                        value: recordCountDown,
                      ),
                    ),
                  ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  void captureOneFrame() {
    setState(() {
      title = i18nBook.realTimeConsultation.captureVid.t;
    });
    widget.onTap();
  }

  void startRecord() {
    setState(() {
      title = i18nBook.realTimeConsultation.recording.t;
      recordCountDown = 1;
      isRecording = true;
    });
    widget.onStartRecord();
    startTime = DateTime.now();

    /// 改用 recordTimer ，倒计时结束后取消 recordTimer
    recordTimer = Timer.periodic(Duration(milliseconds: 100), (timer) {
      if (startTime != null) {
        setState(() {
          recordCountDown = 1 -
              (DateTime.now().difference(startTime!).inMilliseconds /
                  maxRecordTime /
                  1000);
        });
        if (recordCountDown <= 0) {
          stopRecord();
        }
      }
    });
  }

  void stopRecord() {
    recordTimer?.cancel();
    recordTimer = null;
    setState(() {
      title = i18nBook.realTimeConsultation.captureVid.t;
      isRecording = false;
    });
    widget.onStopRecord();
  }
}

class RecordButton4Mobile extends FStatefulWidget
    implements FInteractiveContainer {
  RecordButton4Mobile({
    required this.onStartRecord,
    required this.onStopRecord,
  });

  @override
  FState<FStatefulWidget> createState() {
    return _RecordButton4MobileState();
  }

  /// 开始录制
  final Function onStartRecord;

  /// 结束录制
  final Function onStopRecord;

  @override
  String get pageName => "RecordButton";
}

class _RecordButton4MobileState extends FState<RecordButton4Mobile> {
  /// 录制开始时间
  DateTime? startTime;

  /// 最大录制时长 s
  static const int maxRecordTime = 30;

  /// 录制剩余时间百分比
  double recordCountDown = 0;

  /// 是否正在录制
  bool isRecording = false;

  /// 录制计时器
  Timer? recordTimer;

  @override
  void initState() {
    super.initState();
  }

  @override
  FWidget build(BuildContext context) {
    return FGestureDetector(
      name: "RecordButton",
      businessParent: this.widget,
      onTap: _notification,
      onLongPressStart: (details) {
        _startRecord();
      },
      onLongPressEnd: (details) {
        _stopRecord();
      },
      child: FIcon(
        Icons.videocam,
        size: 30,
        color: Colors.white,
      ),
    );
  }

  void _notification() {
    PromptBox.toast(i18nBook.realTimeConsultation.longPressToRecord.t);
  }

  void _startRecord() {
    setState(() {
      isRecording = true;
    });
    HapticFeedback.mediumImpact();
    widget.onStartRecord();
    startTime = DateTime.now();

    /// 改用 recordTimer ，倒计时结束后取消 recordTimer
    recordTimer = Timer.periodic(Duration(milliseconds: 100), (timer) {
      if (startTime != null) {
        setState(() {
          recordCountDown = 1 -
              (DateTime.now().difference(startTime!).inMilliseconds /
                  maxRecordTime /
                  1000);
        });
        if (recordCountDown <= 0) {
          _stopRecord();
        }
      }
    });
  }

  void _stopRecord() {
    recordTimer?.cancel();
    recordTimer = null;
    setState(() {
      isRecording = false;
    });

    /// 调用手机震动
    HapticFeedback.mediumImpact();
    widget.onStopRecord();
  }
}
