import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'dart:math';
import 'package:kaer_with_panels/app/modules/kr_home/controllers/kr_home_controller.dart';
import 'package:kaer_with_panels/app/common/app_run_data.dart';
import 'package:kaer_with_panels/app/model/response/kr_user_available_subscribe.dart';
import 'package:kaer_with_panels/app/utils/kr_log_util.dart';
import 'package:kaer_with_panels/app/localization/app_translations.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:kaer_with_panels/app/widgets/dialogs/kr_dialog.dart';

class KRHomeSubscriptionView extends GetView<KRHomeController> {
  const KRHomeSubscriptionView({super.key});

  @override
  Widget build(BuildContext context) {
    return Obx(() {
      if (!KRAppRunData().kr_isLogin.value) {
        return const SizedBox.shrink();
      }

      final currentSubscribe =
          controller.kr_subscribeService.kr_currentSubscribe.value;
      if (currentSubscribe == null) {
        return const SizedBox.shrink();
      }

      KRLogUtil.kr_i('当前订阅名称: ${currentSubscribe.name}',
          tag: 'SubscriptionView');

      final totalTraffic = currentSubscribe.traffic;
      final usedTraffic = currentSubscribe.download + currentSubscribe.upload;
      final hasTrafficLimit = totalTraffic > 0;
      var trafficPercentage =
          hasTrafficLimit ? (usedTraffic / totalTraffic).clamp(0.0, 1.0) : 0.0;

      return Container(
        padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(
              Icons.bolt_rounded,
              size: 14.w,
              color: Theme.of(context).brightness == Brightness.light
                  ? Colors.black54
                  : Colors.white54,
            ),
            SizedBox(width: 4.w),
            Expanded(
              child: Text(
                currentSubscribe.name,
                style: TextStyle(
                  color: Theme.of(context).brightness == Brightness.light
                      ? Colors.black
                      : Colors.white,
                  fontSize: 12.sp,
                  fontWeight: FontWeight.w500,
                ),
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              ),
            ),
            SizedBox(width: 4.w),
            Container(
              height: 3.h,
              width: 20.w,
              decoration: BoxDecoration(
                color: Theme.of(context).brightness == Brightness.light
                    ? Colors.grey[200]
                    : Colors.grey[800],
                borderRadius: BorderRadius.circular(1.5.r),
              ),
              child: FractionallySizedBox(
                alignment: Alignment.centerLeft,
                widthFactor: trafficPercentage,
                child: Container(
                  decoration: BoxDecoration(
                    color: _getTrafficColor(trafficPercentage),
                    borderRadius: BorderRadius.circular(1.5.r),
                  ),
                ),
              ),
            ),
            SizedBox(width: 4.w),
            Icon(
              Icons.swap_horiz,
              size: 14.w,
              color: Theme.of(context).brightness == Brightness.light
                  ? Colors.black.withOpacity(0.5)
                  : Colors.white.withOpacity(0.5),
            ),
          ],
        ),
      );
    });
  }

  Widget _buildLoadingView(BuildContext context) {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [
            Theme.of(context).brightness == Brightness.light
                ? Colors.white
                : Colors.grey[900]!,
            Theme.of(context).brightness == Brightness.light
                ? Colors.grey[50]!
                : Colors.grey[800]!,
          ],
        ),
        borderRadius: BorderRadius.circular(24),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            blurRadius: 15,
            offset: const Offset(0, 5),
          ),
        ],
      ),
      child: Row(
        children: [
          const SizedBox(
            width: 24,
            height: 24,
            child: CircularProgressIndicator(
              strokeWidth: 2,
            ),
          ),
          const SizedBox(width: 16),
          Text(
            AppTranslations.kr_home.loading,
            style: TextStyle(
              color: Theme.of(context).brightness == Brightness.light
                  ? Colors.black
                  : Colors.white,
              fontSize: 16,
              fontWeight: FontWeight.w500,
            ),
          ),
        ],
      ),
    );
  }

  IconData _getStatusIcon(KRUserAvailableSubscribeItem subscribe) {
    final now = DateTime.now();
    final expireTime = DateTime.parse(subscribe.expireTime);
    final difference = expireTime.difference(now);

    if (difference.isNegative) {
      return Icons.error_outline_rounded;
    } else if (difference.inDays <= 1) {
      return Icons.warning_amber_rounded;
    } else {
      return Icons.check_circle_outline_rounded;
    }
  }

  Color _getStatusColor(
      BuildContext context, KRUserAvailableSubscribeItem subscribe) {
    final now = DateTime.now();
    final expireTime = DateTime.parse(subscribe.expireTime);
    final difference = expireTime.difference(now);

    if (difference.isNegative) {
      return Colors.red;
    } else if (difference.inDays <= 1) {
      return Colors.orange;
    } else {
      return const Color(0xFF00E52B);
    }
  }

  String _getStatusText(KRUserAvailableSubscribeItem subscribe) {
    final now = DateTime.now();
    final expireTime = DateTime.parse(subscribe.expireTime);
    final difference = expireTime.difference(now);

    if (difference.isNegative) {
      return '已过期';
    } else if (difference.inDays <= 1) {
      return '即将到期';
    } else {
      return '有效';
    }
  }

  Color _getTrafficColor(double percentage) {
    if (percentage >= 0.9) {
      return Colors.red;
    } else if (percentage >= 0.7) {
      return Colors.orange;
    } else {
      return const Color(0xFF00E52B);
    }
  }

  String _formatTraffic(int bytes) {
    if (bytes < 1024) {
      return '$bytes B';
    } else if (bytes < 1024 * 1024) {
      return '${(bytes / 1024).toStringAsFixed(1)} KB';
    } else if (bytes < 1024 * 1024 * 1024) {
      return '${(bytes / (1024 * 1024)).toStringAsFixed(1)} MB';
    } else {
      return '${(bytes / (1024 * 1024 * 1024)).toStringAsFixed(1)} GB';
    }
  }

  String _formatDate(String dateStr) {
    try {
      final date = DateTime.parse(dateStr);
      return '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}';
    } catch (e) {
      return dateStr;
    }
  }
}
