import 'dart:async';

import 'package:clean/utils/expand.dart';
import 'package:flutter/Material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class CountdownTimer extends StatefulWidget {
  final Duration duration;

  const CountdownTimer({super.key, required this.duration});

  @override
  State<CountdownTimer> createState() => _CountdownTimerState();
}

class _CountdownTimerState extends State<CountdownTimer> {
  late Timer _timer;
  late Duration _remainingTime;

  @override
  void initState() {
    super.initState();
    _remainingTime = widget.duration;
    _startTimer();
  }

  void _startTimer() {
    // 使用16毫秒的间隔来更新UI，确保毫秒的显示更流畅
    _timer = Timer.periodic(const Duration(milliseconds: 16), (timer) {
      setState(() {
        if (_remainingTime.inMilliseconds <= 0) {
          _timer.cancel();
        } else {
          _remainingTime = _remainingTime - const Duration(milliseconds: 16);
        }
      });
    });
  }

  @override
  void dispose() {
    _timer.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // 计算分、秒、毫秒
    int minutes = _remainingTime.inMinutes;
    int seconds = (_remainingTime.inSeconds % 60);
    int milliseconds = (_remainingTime.inMilliseconds % 1000) ~/ 10; // 取前两位

    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        _buildTimeBox(minutes.toString().padLeft(2, '0')),
        SizedBox(width: 10.w),
        _buildSeparator(),
        SizedBox(width: 10.w),
        _buildTimeBox(seconds.toString().padLeft(2, '0')),
        SizedBox(width: 10.w),
        _buildSeparator(),
        SizedBox(width: 10.w),
        _buildTimeBox(milliseconds.toString().padLeft(2, '0')),
      ],
    );
  }

  Widget _buildTimeBox(String value) {
    return Container(
      width: 60.w,
      height: 60.w,
      decoration: BoxDecoration(
        color: Colors.black,
        borderRadius: BorderRadius.circular(12.r),
        border: Border.all(
          color: "#343947".color,
          width: 1.w,
        ),
      ),
      child: Center(
        child: Text(
          value,
          style: TextStyle(
            color: Colors.white,
            fontSize: 32.sp,
            fontWeight: FontWeight.bold,
          ),
        ),
      ),
    );
  }

  Widget _buildSeparator() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 8),
      child: Text(
        ':',
        style: TextStyle(
          color: "#343947".color,
          fontSize: 32.sp,
          fontWeight: FontWeight.bold,
        ),
      ),
    );
  }
}
