import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:kaer_with_panels/app/modules/kr_home/controllers/kr_home_controller.dart';
import 'package:kaer_with_panels/app/model/response/kr_user_available_subscribe.dart';
import 'package:kaer_with_panels/app/localization/app_translations.dart';
import 'package:kaer_with_panels/app/widgets/kr_app_text_style.dart';

class KRSubscribeSelectorView extends StatelessWidget {
  final KRHomeController? controller;

  const KRSubscribeSelectorView({
    super.key,
    this.controller,
  });

  @override
  Widget build(BuildContext context) {
    final homeController = controller ?? Get.find<KRHomeController>();
    final isDarkMode = Theme.of(context).brightness == Brightness.dark;
    
    return Container(
      width: MediaQuery.of(context).size.width * 0.85,
      decoration: BoxDecoration(
        color: Theme.of(context).primaryColor,
        borderRadius: BorderRadius.circular(20.r),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            blurRadius: 10.r,
            offset: Offset(0, 2.w),
            spreadRadius: 0,
          ),
        ],
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
            padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.w),
            decoration: BoxDecoration(
              color: Colors.blue.withOpacity(0.05),
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(20.r),
                topRight: Radius.circular(20.r),
              ),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  AppTranslations.kr_purchaseMembership.selectPackage,
                  style: KrAppTextStyle(
                    fontSize: 15,
                    fontWeight: FontWeight.w600,
                    color: Theme.of(context).textTheme.titleLarge?.color,
                  ),
                ),
                Material(
                  color: Colors.transparent,
                  child: InkWell(
                    onTap: () => Navigator.pop(context),
                    borderRadius: BorderRadius.circular(20.r),
                    child: Padding(
                      padding: EdgeInsets.all(4.w),
                      child: Icon(
                        Icons.close_rounded,
                        color: Theme.of(context).textTheme.bodyLarge?.color?.withOpacity(0.6),
                        size: 18.w,
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
          Obx(() {
            final subscribes = homeController.kr_subscribeService.kr_availableSubscribes;
            if (subscribes.isEmpty) {
              return Padding(
                padding: EdgeInsets.symmetric(vertical: 16.w, horizontal: 12.w),
                child: Column(
                  children: [
                    Icon(
                      Icons.subscriptions_outlined,
                      size: 48.w,
                      color: Theme.of(context).textTheme.bodyLarge?.color?.withOpacity(0.3),
                    ),
                    SizedBox(height: 12.w),
                    Text(
                      AppTranslations.kr_purchaseMembership.noData,
                      style: KrAppTextStyle(
                        fontSize: 15,
                        fontWeight: FontWeight.w500,
                        color: Theme.of(context).textTheme.bodyLarge?.color?.withOpacity(0.5),
                      ),
                    ),
                  ],
                ),
              );
            }
            return ConstrainedBox(
              constraints: BoxConstraints(
                maxHeight: MediaQuery.of(context).size.height * 0.5,
              ),
              child: ListView.builder(
                shrinkWrap: true,
                padding: EdgeInsets.symmetric(vertical: 4.w, horizontal: 4.w),
                itemCount: subscribes.length,
                itemBuilder: (context, index) {
                  final subscribe = subscribes[index];
                  final isCurrent = subscribe.id == homeController.kr_subscribeService.kr_currentSubscribe.value?.id;
               
                  return _SubscribeItem(
                    subscribe: subscribe,
                    isCurrent: isCurrent,
                    onTap: ()  {
                       homeController.kr_switchSubscribe(subscribe);
                       Get.back();
                    },
                  );
                },
              ),
            );
          }),
          SizedBox(height: 8.w),
        ],
      ),
    );
  }
}

class _SubscribeItem extends StatelessWidget {
  final KRUserAvailableSubscribeItem subscribe;
  final bool isCurrent;
  final VoidCallback onTap;

  const _SubscribeItem({
    required this.subscribe,
    required this.isCurrent,
    required this.onTap,
  });

  @override
  Widget build(BuildContext context) {
    final usedTraffic = (subscribe.download + subscribe.upload) / 1024 / 1024 / 1024;
    final totalTraffic = subscribe.traffic / 1024 / 1024 / 1024;
    var percentage = totalTraffic > 0 ? usedTraffic / totalTraffic : 0.0;

    final isDarkMode = Theme.of(context).brightness == Brightness.dark;
    final isUnlimited = subscribe.traffic == 0;

    String getUsedTrafficDisplay() {
      if (usedTraffic < 1) {
        return '${(usedTraffic * 1024).toStringAsFixed(2)}MB';
      } else {
        return '${usedTraffic.toStringAsFixed(2)}GB';
      }
    }

    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 2.w),
      child: Material(
        color: Colors.transparent,
        child: InkWell(
          onTap: onTap,
          borderRadius: BorderRadius.circular(12.r),
          child: Ink(
            padding: EdgeInsets.all(12.w),
            decoration: BoxDecoration(
              color: isCurrent
                  ? Colors.blue.withOpacity(isDarkMode ? 0.15 : 0.08)
                  : Theme.of(context).cardColor,
              borderRadius: BorderRadius.circular(12.r),
              border: Border.all(
                color: isCurrent
                    ? Colors.blue.withOpacity(isDarkMode ? 0.5 : 0.3)
                    : Theme.of(context).dividerColor.withOpacity(0.3),
                width: 1,
              ),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Expanded(
                      child: Text(
                        subscribe.name,
                        style: KrAppTextStyle(
                          fontSize: 15,
                          fontWeight: FontWeight.w600,
                          color: Theme.of(context).textTheme.titleLarge?.color,
                        ),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                    if (isCurrent)
                      Container(
                        padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 2.w),
                        decoration: BoxDecoration(
                          color: Colors.blue,
                          borderRadius: BorderRadius.circular(16.r),
                          boxShadow: [
                            BoxShadow(
                              color: Colors.blue.withOpacity(0.2),
                              blurRadius: 6.w,
                              offset: Offset(0, 1.w),
                            ),
                          ],
                        ),
                        child: Text(
                          AppTranslations.kr_home.currentConnectionTitle,
                          style: KrAppTextStyle(
                            color: Colors.white,
                            fontSize: 11,
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                      ),
                  ],
                ),
                SizedBox(height: 8.w),
                Text(
                  isUnlimited 
                    ? AppTranslations.kr_purchaseMembership.unlimitedTraffic
                    : '${getUsedTrafficDisplay()} / ${totalTraffic.toStringAsFixed(2)}GB',
                  style: KrAppTextStyle(
                    fontSize: 13,
                    fontWeight: FontWeight.w500,
                    color: Theme.of(context).textTheme.bodyMedium?.color?.withOpacity(0.8),
                  ),
                ),
                if (!isUnlimited) ...[
                  SizedBox(height: 8.w),
                  ClipRRect(
                    borderRadius: BorderRadius.circular(4.r),
                    child: LinearProgressIndicator(
                      value: percentage.clamp(0.0, 1.0),
                      backgroundColor: isDarkMode
                          ? Colors.grey[700]?.withOpacity(0.7)
                          : Colors.grey[300]?.withOpacity(0.9),
                      valueColor: AlwaysStoppedAnimation<Color>(
                        _getTrafficColor(percentage, isDarkMode),
                      ),
                      minHeight: 4.w,
                    ),
                  ),
                ],
              ],
            ),
          ),
        ),
      ),
    );
  }

  Color _getTrafficColor(double percentage, bool isDarkMode) {
    if (percentage >= 0.9) {
      return isDarkMode 
        ? Colors.red.withOpacity(0.8)
        : Colors.red.withOpacity(0.7);
    } else if (percentage >= 0.7) {
      return isDarkMode 
        ? Colors.orange.withOpacity(0.8)
        : Colors.orange.withOpacity(0.7);
    } else {
      return isDarkMode 
        ? Colors.blue.withOpacity(0.8)
        : Colors.blue.withOpacity(0.7);
    }
  }
} 