import 'package:flutter/material.dart';
import 'package:get/get.dart';

class KRSubscriptionExpiryText extends StatelessWidget {
  final String? Function() expireTimeProvider;
  final TextStyle? style;

  const KRSubscriptionExpiryText({
    Key? key,
    required this.expireTimeProvider,
    this.style,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Obx(() {
      final expireTimeStr = expireTimeProvider();
      String expiryText;
      bool highlight = false;

      if (expireTimeStr == null || expireTimeStr.isEmpty) {
        expiryText = '尚未购买套餐';
        highlight = true;
      } else {
        DateTime? expireDateTime;
        try {
          expireDateTime = DateTime.parse(expireTimeStr);
        } catch (_) {
          expireDateTime = null;
        }

        if (expireDateTime == null) {
          expiryText = '套餐信息无效';
        } else if (expireDateTime.isBefore(DateTime.now())) {
          final formattedExpireDate =
              '${expireDateTime.year}/${expireDateTime.month.toString().padLeft(2, '0')}/${expireDateTime.day.toString().padLeft(2, '0')}';
          expiryText = '已于 $formattedExpireDate 到期';
          highlight = true;
        } else {
          final year = expireDateTime.year;
          final month = expireDateTime.month.toString().padLeft(2, '0');
          final day = expireDateTime.day.toString().padLeft(2, '0');
          final hour = expireDateTime.hour.toString().padLeft(2, '0');
          final minute = expireDateTime.minute.toString().padLeft(2, '0');

          final formattedDateTime = '$year/$month/$day $hour:$minute';
          expiryText = '到期时间：$formattedDateTime';
        }
      }

      final baseStyle = style ??
          const TextStyle(
            color: Colors.white,
            fontSize: 12,
          );
      final appliedStyle = highlight
          ? baseStyle.copyWith(color: const Color(0xFFFF00B7))
          : baseStyle;

      return Text(
        expiryText,
        style: appliedStyle,
      );
    });
  }
}
