import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../../../localization/app_translations.dart';
import '../../../widgets/kr_app_text_style.dart';
import '../../../widgets/kr_loading_animation.dart';
import '../controllers/kr_home_controller.dart';
import '../models/kr_home_views_status.dart';
import 'kr_home_connection_info_view.dart';
import 'kr_home_connection_options_view.dart';
import 'kr_home_node_list_view.dart';
import '../widgets/kr_subscription_card.dart';
import 'kr_home_trial_card.dart';
import 'kr_home_last_day_card.dart';
import '../../../utils/kr_log_util.dart';

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

  @override
  Widget build(BuildContext context) {
    return Obx(() {
      final currentStatus = controller.kr_currentListStatus.value;

      KRLogUtil.kr_i('构建底部面板', tag: 'HomeBottomPanel');
      KRLogUtil.kr_i('当前视图状态: ${controller.kr_currentViewStatus.value}',
          tag: 'HomeBottomPanel');
      KRLogUtil.kr_i('当前高度: ${controller.kr_bottomPanelHeight.value}',
          tag: 'HomeBottomPanel');

      if (controller.kr_currentListStatus.value ==
          KRHomeViewsListStatus.kr_loading) {
        return _kr_buildLoadingView();
      }

      if (controller.kr_currentListStatus.value ==
          KRHomeViewsListStatus.kr_error) {
        return _kr_buildErrorView(context);
      }

      if (currentStatus == KRHomeViewsListStatus.kr_serverList ||
          currentStatus == KRHomeViewsListStatus.kr_countrySubscribeList ||
          currentStatus == KRHomeViewsListStatus.kr_serverSubscribeList ||
          currentStatus == KRHomeViewsListStatus.kr_subscribeList) {
        return const KRHomeNodeListView();
      }

      return _kr_buildDefaultView(context);
    });
  }

  Widget _kr_buildDefaultView(BuildContext context) {
    // 使用 GetX 的 .obs 变量来避免重复访问
    final hasValidSubscription =
        controller.kr_subscribeService.kr_currentSubscribe.value != null;
    final isTrial = controller.kr_subscribeService.kr_isTrial;
    final isLastDay = controller.kr_subscribeService.kr_isLastDayOfSubscription;
    final isNotLoggedIn = controller.kr_currentViewStatus.value ==
        KRHomeViewsStatus.kr_notLoggedIn;

    KRLogUtil.kr_i('构建默认视图', tag: 'HomeBottomPanel');
    KRLogUtil.kr_i('是否未登录: $isNotLoggedIn', tag: 'HomeBottomPanel');
    KRLogUtil.kr_i('是否有有效订阅: $hasValidSubscription', tag: 'HomeBottomPanel');
    KRLogUtil.kr_i('是否试用: ${isTrial.value}', tag: 'HomeBottomPanel');
    KRLogUtil.kr_i('当前高度: ${controller.kr_bottomPanelHeight.value}',
        tag: 'HomeBottomPanel');

    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        // 主要内容区域
        if (isNotLoggedIn)
          // 未登录状态下，使用 SingleChildScrollView 让内容自然撑开
          SingleChildScrollView(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Padding(
                  padding:
                      EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.w),
                  child: const KRHomeConnectionOptionsView(),
                ),
              ],
            ),
          )
        else
          // 已登录状态下，使用固定高度
          Expanded(
            child: SingleChildScrollView(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  // 1. 如果已订阅，展示当前连接卡片
                  if (hasValidSubscription)
                    Container(
                        margin: EdgeInsets.only(top: 12.h),
                        child: const KRHomeConnectionInfoView())
                  else
                    Container(
                        margin:
                            EdgeInsets.only(top: 12.h, left: 12.w, right: 12.w),
                        child: const KRSubscriptionCard()),

                  // 2. 如果已订阅且是试用，展示试用卡片
                  if (hasValidSubscription && isTrial.value)
                    Container(
                      margin: EdgeInsets.only(top: 12.h),
                      child: const KRHomeTrialCard(),
                    ),

                  // 3. 如果已订阅且是最后一天，展示最后一天卡片
                  if (hasValidSubscription && isLastDay.value && !isTrial.value)
                    Container(
                      margin: EdgeInsets.only(top: 12.h),
                      child: const KRHomeLastDayCard(),
                    ),

                  // 4. 连接选项（分组和国家入口）
                  Padding(
                    padding:
                        EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.w),
                    child: const KRHomeConnectionOptionsView(),
                  ),
                ],
              ),
            ),
          ),
      ],
    );
  }

  Widget _kr_buildLoadingView() {
    KRLogUtil.kr_i('构建加载视图', tag: 'HomeBottomPanel');
    KRLogUtil.kr_i('当前高度: ${controller.kr_bottomPanelHeight.value}',
        tag: 'HomeBottomPanel');

    return Center(
      child: CircularProgressIndicator(
        color: Colors.green,
        strokeWidth: 2.0,
      ),
    );
  }

  Widget _kr_buildErrorView(BuildContext context) {
    return Container(
      height: 200.w,
      padding: EdgeInsets.all(16.w),
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.error_outline,
              size: 48.w,
              color: Theme.of(context).colorScheme.error,
            ),
            SizedBox(height: 16.w),
            Text(
              AppTranslations.kr_home.error,
              style: KrAppTextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w500,
                color: Theme.of(context).textTheme.bodyMedium?.color,
              ),
            ),
            SizedBox(height: 8.w),
            Text(
              AppTranslations.kr_home.checkNetwork,
              style: KrAppTextStyle(
                fontSize: 14,
                color: Theme.of(context).textTheme.bodySmall?.color,
              ),
            ),
            SizedBox(height: 24.w),
            SizedBox(
              width: 200.w,
              height: 44.h,
              child: ElevatedButton(
                onPressed: () => controller.kr_refreshAll(),
                style: ElevatedButton.styleFrom(
                  backgroundColor: Theme.of(context).colorScheme.primary,
                  foregroundColor: Theme.of(context).colorScheme.onPrimary,
                  elevation: 0,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(8.r),
                  ),
                ),
                child: Text(
                  AppTranslations.kr_home.retry,
                  style: KrAppTextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
