import 'dart:async';

import 'package:fis_ui/index.dart';
import 'package:fis_ui/values/font_sizes.dart';
import 'package:fis_ui/values/spacings.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/rpc.dart';

/// 窗口录制控制器
class WindowRecorderController {
  WindowRecorderController(this.title);

  DateTime? _lastTime;
  Timer? _timer;
  final _duration = FRx<Duration>(Duration.zero);
  final _running = FRxBool(false);

  final String title;

  /// 时长
  Duration get duration => _duration.value;

  /// 是否在录制
  bool get running => _running.value;

  /// 开始
  Future<void> start() async {
    await rpc.platform.startRecording(title, "");
    _startTimer();
  }

  /// 结束
  Future<void> stop() async {
    _stopTimer();
    _lastTime = null;
    await rpc.platform.stopRecording();
  }

  /// 暂停
  Future<void> pause() async {
    await rpc.platform.pauseRecording(true);
    _pauseTimer();
  }

  /// 继续
  Future<void> resume() async {
    await rpc.platform.pauseRecording(false);
    _reStartTimer();
  }

  void _startTimer() {
    if (_timer != null) {
      _stopTimer();
    }
    _reStartTimer();
  }

  void _pauseTimer() {
    _timer?.cancel();
    _running.value = false;
  }

  void _stopTimer() {
    _timer?.cancel();
    _timer = null;
    _duration.value = Duration.zero;
    _running.value = false;
  }

  void _reStartTimer() {
    _lastTime = DateTime.now();
    _timer = Timer.periodic(
      const Duration(milliseconds: 10),
      (timer) {
        final now = DateTime.now();
        final ms = now.difference(_lastTime!).abs().inMilliseconds;
        _lastTime = now;
        // 计算累计时长
        final total = duration.inMilliseconds + ms;
        _duration.value = Duration(milliseconds: total);
      },
    );
    _running.value = true;
  }
}

/// 窗口录制标记
class WindowRecorderMark extends FStatelessWidget {
  WindowRecorderMark({
    required this.controller,
    super.key,
  });

  final WindowRecorderController controller;

  @override
  FWidget build(BuildContext context) {
    return FRow(
      // mainAxisAlignment: MainAxisAlignment.center,
      mainAxisSize: MainAxisSize.min,
      children: [
        FIcon(
          Icons.radio_button_checked,
          color: Colors.red,
          size: FFontSizes.H4,
        ),
        FSizedBox(width: FSpacings.S),
        _buildDuration(),
      ],
    );
  }

  FWidget _buildDuration() {
    return FObx(() {
      final duration = controller.duration;
      final totalMs = duration.inMilliseconds;
      int minutes = (totalMs / (1000 * 60)).floor();
      int seconds = (totalMs / 1000 % 60).floor();
      int milliseconds = (totalMs % 1000 ~/ 10);

      String minStr = minutes.toString().padLeft(2, '0');
      String secStr = seconds.toString().padLeft(2, '0');
      String msStr = milliseconds.toString().padLeft(3, '0');

      final content = "REC $minStr:$secStr.$msStr";
      return FText(
        content,
        style: const TextStyle(fontSize: FFontSizes.H3, color: Colors.white),
      );
    });
  }
}
