import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'dart:async';

import 'package:yumi/app_localizations.dart';
import 'package:yumi/ui_kit/components/text/sc_text.dart';

class CountdownTimer extends StatefulWidget {
  final DateTime expiryDate;
  final Color? color;
  final double? fontSize;
  final FontWeight? fontWeight;

  const CountdownTimer({
    super.key,
    required this.expiryDate,
    this.color,
    this.fontSize,
    this.fontWeight,
  });

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

class _CountdownTimerState extends State<CountdownTimer> {
  Timer? _timer;
  Duration _remainingTime = Duration.zero;

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

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

  void _calculateRemainingTime() {
    final now = DateTime.now();
    if (widget.expiryDate.isAfter(now)) {
      setState(() {
        _remainingTime = widget.expiryDate.difference(now);
      });
    } else {
      setState(() {
        _remainingTime = Duration.zero;
      });
    }
  }

  void _startTimer() {
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      _calculateRemainingTime();
    });
  }

  String _formatDuration(Duration duration) {
    if (duration.inSeconds <= 0) {
      return SCAppLocalizations.of(context)!.expired;
    }

    String twoDigits(int n) => n.toString().padLeft(2, '0');

    final days = duration.inDays;
    final hours = twoDigits(duration.inHours.remainder(24));
    final minutes = twoDigits(duration.inMinutes.remainder(60));
    final seconds = twoDigits(duration.inSeconds.remainder(60));

    if (days > 0) {
      return '${days}D $hours:$minutes:$seconds';
    }
    return '$hours:$minutes:$seconds';
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        text(
          _formatDuration(_remainingTime),
          fontSize: widget.fontSize ?? 14.sp,
          fontWeight: widget.fontWeight ?? FontWeight.bold,
          textColor:
              _remainingTime.inSeconds <= 0
                  ? Colors.grey
                  : (widget.color ?? Colors.black),
        ),
      ],
    );
  }
}
