import 'package:collection/collection.dart';
import 'package:flutter/Material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:keyboard/base/base_page.dart';
import 'package:keyboard/data/repository/account_repository.dart';
import 'package:keyboard/dialog/login/login_dialog.dart';
import 'package:keyboard/module/profile/profile_page.dart';
import 'package:keyboard/module/zodiac_love_intimacy/tody/zodiac_love_today_view.dart';
import 'package:keyboard/module/zodiac_love_intimacy/zodiac_love_intimacy_controller.dart';
import 'package:keyboard/resource/colors.gen.dart';
import 'package:keyboard/router/app_page_arguments.dart';
import 'package:keyboard/utils/toast_util.dart';
import 'package:lottie/lottie.dart';
import 'package:nested_scroll_views/material.dart';
import '../../data/repository/keyboard_repository.dart';
import '../../di/get_it.dart';
import '../../resource/assets.gen.dart';
import '../../resource/string.gen.dart';
import '../../router/app_pages.dart';
import '../../utils/age_zodiac_sign_util.dart';
import '../../widget/avatar/avatar_image_widget.dart';
import '../../widget/status_bar_placeholder_widget.dart';
import '../../widget/top_bar.dart';
import '../user_profile/user_profile_page.dart';
import 'enums/zodiac_love_intimacy_tab.dart';
import 'future_week/zodiac_love_future_week_view.dart';

/// 星座恋爱分析Tab页
class ZodiacLoveIntimacyPage extends BasePage<ZodiacLoveIntimacyController> {
  const ZodiacLoveIntimacyPage({super.key});

  static start({ZodiacLoveIntimacyTab tab = ZodiacLoveIntimacyTab.today}) {
    var accountRepository = getIt.get<AccountRepository>();
    var keyboardRepository = getIt.get<KeyboardRepository>();

    // 未登录，要求先登录
    if (!accountRepository.isLogin.value) {
      ToastUtil.show(StringName.accountNoLogin);
      LoginDialog.show();
      return;
    }

    // 如果用户未设置生日，则要求先设置生日，才能跳转
    if (accountRepository.userInfo.value?.birthday == null) {
      ToastUtil.show(StringName.userNotSetBirthdayTip);
      UserProfilePage.start();
      return;
    }

    // 未选择档案，要求先创建或选择档案
    if (keyboardRepository.chooseKeyboardInfo.value == null) {
      ToastUtil.show(StringName.userNotCreateProfile);
      ProfilePage.start();
      return;
    }

    var args = {AppPageArguments.index: tab.tabIndex};
    Get.toNamed(RoutePath.zodiacLoveIntimacy, arguments: args);
  }

  @override
  bool immersive() {
    return true;
  }

  @override
  bool statusBarDarkFont() {
    return false;
  }

  @override
  backgroundColor() {
    return Colors.transparent;
  }

  @override
  Widget buildBody(BuildContext context) {
    return Scaffold(
      backgroundColor: backgroundColor(),
      body: Stack(
        children: [
          // 背景图
          Positioned.fill(child: _buildBackgroundImage()),
          // 内容，填充剩余部分
          Positioned.fill(
            top: 0,
            left: 0,
            right: 0,
            bottom: 0,
            child: _buildContent(context),
          ),
          // 状态栏和标题栏
          Positioned(
            left: 0,
            top: 0,
            right: 0,
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [StatusBarPlaceholderWidget(), _buildTopBar()],
            ),
          ),
        ],
      ),
    );
  }

  /// 背景图
  Widget _buildBackgroundImage() {
    return Container(
      child: Assets.images.bgZodiacLoveIntimacy.image(
        fit: BoxFit.cover,
        width: double.infinity,
        height: double.infinity,
      ),
    );
  }

  /// 顶部栏
  Widget _buildTopBar() {
    return TopBar(
      leftWidget: GestureDetector(
        onTap: controller.clickBack,
        child: Assets.images.iconWhiteBackArrow.image(
          width: 24.w,
          height: 24.h,
        ),
      ),
      centerWidget: Text(
        StringName.zodiacLoveIntimacy,
        style: TextStyle(
          color: ColorName.white,
          fontSize: 17.sp,
          fontWeight: FontWeight.w500,
        ),
      ),
    );
  }

  /// 指示器
  Widget _buildTabBar() {
    return Obx(() {
      return PreferredSize(
        preferredSize: Size.fromHeight(45.h),
        child: Stack(
          children: [
            Positioned(
              left: 0,
              right: 0,
              top: 8.h,
              child: Container(
                height: 41.h,
                // 顶部2边圆角
                decoration: BoxDecoration(
                  color: Color(0xFFEBE7FD),
                  borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(45.r),
                    topRight: Radius.circular(45.r),
                  ),
                ),
              ),
            ),
            // Tab
            TabBar(
              // 只有2个Tab，均分宽度，所以不可以滚动
              isScrollable: false,
              // 去除底部的黑线
              dividerHeight: 0,
              // 去掉自带的指示器
              indicator: BoxDecoration(),
              // 对齐方式，填充式对齐
              tabAlignment: TabAlignment.fill,
              // 指示器的高度设置为0，才能完全隐藏，否则还是会有一条线的高度
              indicatorWeight: 0,
              // 移除左右边距
              padding: EdgeInsets.zero,
              // 移除指示器与标签的间距
              indicatorPadding: EdgeInsets.zero,
              // 移除标签内部边距
              labelPadding: EdgeInsets.zero,
              // 配置Tab数据
              tabs:
                  controller.tabBarList.mapIndexed((
                    int index,
                    ZodiacLoveIntimacyTab tab,
                  ) {
                    bool isSelected = controller.currentTabIndex.value == index;
                    return _buildTab(tab, isSelected);
                  }).toList(),
              controller: controller.tabController,
              onTap: (index) {
                controller.handleTabChange(index);
              },
            ),
          ],
        ),
      );
    });
  }

  /// 每个Tab
  Tab _buildTab(ZodiacLoveIntimacyTab tab, bool isSelected) {
    String tabName = tab.getTabName();
    TextStyle tabTextStyle;
    if (isSelected) {
      // 选中时的颜色
      tabTextStyle = TextStyle(
        fontSize: 14.sp,
        fontWeight: FontWeight.w700,
        color: ColorName.black80,
      );
    } else {
      // 未选中时的颜色
      tabTextStyle = TextStyle(
        fontSize: 14.sp,
        fontWeight: FontWeight.w600,
        color: ColorName.black60,
      );
    }
    return Tab(
      child: Container(
        width: double.infinity,
        height: double.infinity,
        // 未选中时，距离顶部有一定距离，选中时则撑满TabBar
        margin: EdgeInsets.only(top: isSelected ? 0 : 6.h),
        decoration: BoxDecoration(
          image:
              // 选中时，才有背景图
              isSelected
                  ? DecorationImage(
                    image: tab.getTabSelectedBg(),
                    fit: BoxFit.fill,
                  )
                  : null,
        ),
        child: Center(
          child: Container(
            margin: EdgeInsets.only(top: 5.h),
            child: Text(tabName, style: tabTextStyle),
          ),
        ),
      ),
    );
  }

  /// 内容
  Widget _buildContent(BuildContext context) {
    return Column(
      children: [
        // 顶部基础信息
        _buildTopBasicInfoHeader(),
        // TabBar
        _buildTabBar(),
        // PageView
        Expanded(child: _buildPage()),
      ],
    );
  }

  /// 顶部基础信息视图
  Widget _buildTopBasicInfoHeader() {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        SizedBox(height: 70.w),
        // 头像布局
        _buildAvatarLayout(),
        SizedBox(height: 14.w),
        // 星座梗语与解读
        _buildZodiacDesc(),
        SizedBox(height: 16.w),
      ],
    );
  }

  /// 头像布局
  Widget _buildAvatarLayout() {
    return Obx(() {
      String? myAvatar =
          controller.zodiacLoveIntimacyLoveInfoResponse.value?.imageUrl ?? "";
      if (myAvatar.isEmpty) {
        myAvatar = controller.userInfo.value?.imageUrl ?? "";
      }
      return Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          // 我的头像
          _buildAvatarAndZodiac(
            imageUrl: myAvatar,
            zodiac: controller.myZodiacInfo,
          ),
          // 爱心动画
          Lottie.asset(
            Assets.anim.animNewUserData,
            repeat: true,
            width: 131.w,
            fit: BoxFit.contain,
          ),
          // Ta的头像
          _buildAvatarAndZodiac(
            imageUrl:
                controller
                    .zodiacLoveIntimacyLoveInfoResponse
                    .value
                    ?.targetImageUrl,
            zodiac: controller.taZodiacInfo,
          ),
        ],
      );
    });
  }

  /// 头像和星座
  Widget _buildAvatarAndZodiac({
    required String? imageUrl,
    required Zodiac? zodiac,
  }) {
    return Column(
      children: [
        SizedBox(height: 20.w),
        // 头像
        CircleAvatarWidget(
          image: Assets.images.iconKeyboardDefaultAvatar.provider(),
          imageUrl: imageUrl,
          size: 88.w,
          borderColor: Colors.white,
          borderWidth: 2.r,
          placeholder: (_, __) => const SizedBox.shrink(),
        ),
        SizedBox(height: 14.w),
        // 星座
        Builder(
          builder: (context) {
            if (zodiac != null) {
              return Row(
                children: [
                  zodiac.image.image(width: 14.w, height: 14.w),
                  SizedBox(width: 4.w),
                  Text(
                    zodiac.name,
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 15.sp,
                      fontWeight: FontWeight.w700,
                    ),
                  ),
                ],
              );
            } else {
              return const SizedBox.shrink();
            }
          },
        ),
      ],
    );
  }

  /// 星座梗语与解读
  Widget _buildZodiacDesc() {
    return Obx(() {
      var info = controller.zodiacLoveIntimacyLoveInfoResponse.value;
      var meme = info?.meme ?? "";
      var explain = info?.explain ?? "";
      // 无数据，不显示
      if (meme.isEmpty && explain.isEmpty) {
        return SizedBox(height: 67.h);
      }
      return Stack(
        alignment: Alignment.center,
        children: [
          Positioned(
            // IntrinsicWidth，包裹内容，宽度不撑大到屏幕宽度
            child: IntrinsicWidth(
              child: Container(
                alignment: Alignment.center,
                padding: EdgeInsets.symmetric(vertical: 8.h, horizontal: 42.w),
                // 圆角背景
                decoration: ShapeDecoration(
                  color: const Color(0x29B80081),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(16.r),
                  ),
                ),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    // 梗语标题
                    Visibility(
                      visible: meme.isNotEmpty,
                      child: Container(
                        margin: EdgeInsets.only(bottom: 2.h),
                        child: Text(
                          meme,
                          textAlign: TextAlign.center,
                          style: TextStyle(
                            color: ColorName.white,
                            fontSize: 12.sp,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ),
                    ),
                    // 星座梗语
                    Visibility(
                      visible: explain.isNotEmpty,
                      child: Text(
                        explain,
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          color: ColorName.white,
                          fontSize: 12.sp,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
          // 左上角的逗号
          Positioned(
            top: 5.w,
            left: 8.w,
            child: Assets.images.iconNewUserZodiacLeft.image(
              width: 13.w,
              height: 13.w,
              fit: BoxFit.contain,
            ),
          ),
          // 右下角的逗号
          Positioned(
            right: 8.w,
            bottom: 5.w,
            child: Assets.images.iconNewUserZodiacRight.image(
              width: 13.w,
              height: 13.w,
              fit: BoxFit.contain,
            ),
          ),
        ],
      );
    });
  }

  /// PageView
  Widget _buildPage() {
    return Obx(() {
      return NestedPageView(
        controller: controller.pageController,
        // 保持页面缓存
        wantKeepAlive: true,
        // 是否禁止滑动切换
        physics:
            controller.isPageViewSwipeEnabled.value
                ? ScrollPhysics()
                : NeverScrollableScrollPhysics(),
        onPageChanged: (index) {
          controller.handlePageChange(index);
        },
        children: [
          // 今日Tab
          ZodiacLoveTodayView(),
          // 未来一周Tab
          ZodiacLoveFutureWeekView(),
        ],
      );
    });
  }
}
