import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:location/base/base_page.dart';
import 'package:location/data/bean/member_status_info.dart';
import 'package:location/resource/assets.gen.dart';
import 'package:location/resource/colors.gen.dart';
import 'package:location/resource/string.gen.dart';
import 'package:location/utils/common_expand.dart';

import '../../router/app_pages.dart';
import '../../utils/common_style.dart';
import '../../utils/date_util.dart';
import '../../widget/common_view.dart';
import 'mine_controller.dart';
import 'mine_trial_membership_countdown_text.dart';

class MinePage extends BasePage<MineController> {
  const MinePage({super.key});

  static void start() {
    Get.toNamed(RoutePath.mine);
  }

  @override
  bool immersive() {
    return true;
  }

  @override
  Color backgroundColor() {
    return '#FAFAFA'.color;
  }

  @override
  Widget buildBody(BuildContext context) {
    return Stack(
      children: [
        Assets.images.bgPageBackground.image(width: double.infinity),
        SafeArea(
          child: SingleChildScrollView(
            child: Column(children: [
              SizedBox(height: 70.w),
              Row(
                children: [
                  SizedBox(width: 12.w),
                  GestureDetector(
                    onTap: () => controller.onEditUserAvatarClick(),
                    child: Obx(() {
                      return controller.isLogin
                          ? (controller.mineInfo.avatar != null
                              ? buildAvatarView(controller.mineInfo.avatar!)
                              : Assets.images.iconMineLogged
                                  .image(width: 54.w, height: 54.w))
                          : Assets.images.iconMineNoLogin
                              .image(width: 54.w, height: 54.w);
                    }),
                  ),
                  SizedBox(width: 10.w),
                  Expanded(child: buildLoginInfo()),
                  //Spacer(),
                  Obx(() {
                    return Visibility(
                        visible: controller.isOpenFreeMember == true,
                        child: GestureDetector(
                            onTap: () => controller.onMemberTryOutClick(),
                            child: buildMemberTryOutView()));
                  })
                ],
              ),
              SizedBox(height: 20.w),
              buildExperienceContent(),
              SizedBox(height: 16.w),
              buildFunList()
            ]),
          ),
        ),
        buildBackBtn(),
      ],
    );
  }

  Widget buildMineFunItem(
      ImageProvider icon, String funName, VoidCallback onTap) {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: onTap,
      child: Container(
        padding: EdgeInsets.symmetric(vertical: 15.w, horizontal: 12.w),
        child: Row(
          children: [
            Image(image: icon, width: 24.w, height: 24.w),
            SizedBox(width: 6.w),
            Text(funName,
                style: TextStyle(fontSize: 15.sp, color: '#202020'.color)),
            Spacer(),
            Assets.images.iconMineFunArrow.image(width: 20.w, height: 20.w)
          ],
        ),
      ),
    );
  }

  Widget buildExperienceContent() {
    return Stack(
      children: [
        Column(
          children: [
            AspectRatio(
                aspectRatio: 332 / 57, child: SizedBox(width: double.infinity)),
            /*Obx(() {
              return Visibility(
                visible: controller.isOpenFreeMember == true,
                child: GestureDetector(
                  onTap: controller.onMemberTryOutClick,
                  child: Stack(
                    children: [
                      Container(
                        margin: EdgeInsets.symmetric(horizontal: 14.w),
                        width: double.infinity,
                        height: 50.w,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.only(
                              bottomLeft: Radius.circular(8.w),
                              bottomRight: Radius.circular(8.w)),
                          gradient: LinearGradient(
                              begin: Alignment.centerLeft,
                              end: Alignment.centerRight,
                              colors: ['#FFF8DA'.color, '#FFF1BA'.color]),
                        ),
                      ),
                      Positioned(
                        bottom: 0,
                        left: 0,
                        right: 0,
                        child: Container(
                          margin: EdgeInsets.symmetric(horizontal: 14.w),
                          height: 32.w,
                          child: Row(
                            children: [
                              SizedBox(width: 15.w),
                              Assets.images.iconExperiment
                                  .image(width: 16.w, height: 16.w),
                              SizedBox(width: 4.w),
                              Text(StringName.memberExperienceVip,
                                  style: TextStyle(
                                      fontSize: 13.sp, color: '#8A5F03'.color)),
                              Spacer(),
                              Text(StringName.memberExperienceVipReceive,
                                  style: TextStyle(
                                      fontSize: 13.sp, color: '#8A5F03'.color)),
                              Assets.images.iconMemberVipReceiveArrow
                                  .image(width: 16.w, height: 16.w),
                              SizedBox(width: 13.w),
                            ],
                          ),
                        ),
                      )
                    ],
                  ),
                ),
              );
            })*/
          ],
        ),
        buildMemberCard()
      ],
    );
  }

  Widget buildLoginInfo() {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: controller.onMineDescClick,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Obx(() {
                String desc = "";
                if (controller.isLogin &&
                    controller.phone?.isNotEmpty == true) {
                  desc = controller.getUserName(controller.phone!);
                } else {
                  desc = StringName.mineAccountGoLogin;
                }
                return Text(desc,
                    style: TextStyle(
                        fontSize: 16.sp,
                        color: '#333333'.color,
                        fontWeight: FontWeight.bold));
              }),
              SizedBox(width: 6.w),
              Obx(() {
                return Visibility(
                    visible: controller.isLogin &&
                        controller.memberStatusInfo != null &&
                        controller.memberStatusInfo?.expired == false,
                    child: Assets.images.iconVip.image(width: 28.w));
              })
            ],
          ),
          SizedBox(height: 6.w),
          buildLoginDesc(),
        ],
      ),
    );
  }

  Container buildMemberTryOutView() {
    return Container(
      margin: EdgeInsets.only(right: 16.w),
      decoration: BoxDecoration(
          color: '#267B7DFF'.color, borderRadius: BorderRadius.circular(26.w)),
      padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 5.w),
      child: Text(
          controller.isLogin
              ? ((controller.memberStatusInfo?.trialed == false)
                  ? StringName.memberTryOut
                  : StringName.memberReceivedMembership)
              : StringName.memberTryOut,
          style: TextStyle(fontSize: 12.sp, color: '#8163FF'.color)),
    );
  }

  Widget buildBackBtn() {
    return SafeArea(
      child: GestureDetector(
          onTap: controller.onBack,
          child: Container(
              margin: EdgeInsets.only(top: 16.w, left: 14.w),
              child: CommonView.getBackBtnView())),
    );
  }

  Widget buildLoginDesc() {
    return Obx(() {
      String txt = '';
      if (!controller.isLogin) {
        txt = StringName.mineNotLoginDesc;
      } else if (controller.memberStatusInfo != null &&
          controller.memberStatusInfo?.expired == false) {
        txt = StringName.mineVip;
      } else if (controller.memberStatusInfo?.expired == true) {
        txt = StringName.mineRenewalVipContinueProtectYou;
      } else {
        txt = StringName.mineOpenVip;
      }
      return Text(txt,
          style: TextStyle(fontSize: 13.sp, color: '#727272'.color));
    });
  }

  Widget buildMemberCard() {
    return Container(
      decoration: BoxDecoration(
          borderRadius: BorderRadius.only(
              topLeft: Radius.circular(20.w),
              topRight: Radius.circular(20.w),
              bottomLeft: Radius.circular(8.w),
              bottomRight: Radius.circular(8.w)),
          gradient: LinearGradient(
              begin: Alignment.centerLeft,
              end: Alignment.centerRight,
              stops: [0.0, 0.1],
              colors: ['#FFF8DA'.color, '#FFF1BA'.color])),
      margin: EdgeInsets.symmetric(horizontal: 14.w),
      child: Column(
        children: [
          GestureDetector(
            onTap: controller.onMemberCardClick,
            child: AspectRatio(
              aspectRatio: 332 / 75,
              child: Container(
                //margin: EdgeInsets.symmetric(horizontal: 14.w),
                decoration: BoxDecoration(
                    image: DecorationImage(
                        image: Assets.images.bgMineMemberCard.provider(),
                        fit: BoxFit.fill)),
                child: Row(
                  children: [
                    SizedBox(width: 14.w),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Row(
                          children: [
                            Assets.images.iconMineUnlockVip.image(width: 68.w),
                            SizedBox(width: 6.5.w),
                            Assets.images.iconMineSmallVip
                                .image(width: 21.6.w, height: 21.6.w),
                          ],
                        ),
                        SizedBox(height: 6.w),
                        buildMemberCardVipDesc()
                      ],
                    ),
                    Spacer(),
                    buildBuyMemberCardBtn()
                  ],
                ),
              ),
            ),
          ),
          Obx(() {
            return Visibility(
                visible: controller.isLogin,
                child: GestureDetector(
                  onTap: !(controller.memberStatusInfo?.trialed ?? false)
                      ? () => controller.onMemberTryOutClick()
                      : null,
                  child: Container(
                    width: double.infinity,
                    padding: EdgeInsets.symmetric(horizontal: 15.w),
                    height: 32.w,
                    child: Row(
                      children: [
                        Assets.images.iconMemberVipSign
                            .image(width: 16.w, height: 16.w),
                        SizedBox(
                          width: 4.w,
                        ),
                        Expanded(
                          child: Obx(() {
                            return MineTrialMembershipCountdownText(
                              memberStatusInfo: controller.memberStatusInfo ??
                                  MemberStatusInfo(
                                      level: 0,
                                      endTimestamp: 0,
                                      expired: false,
                                      permanent: false),
                              trialHasExpiredCallBack:
                                  controller.promptWindowPopsCountdownExpires,
                            );
                          }),
                        ),
                        Visibility(
                            visible: !(controller.memberStatusInfo?.trialed ??
                                false),
                            child: Row(
                              children: [
                                Text(StringName.memberExperienceVipReceive,
                                    style: TextStyle(
                                        fontSize: 13.sp,
                                        color: "#8A5F03".color,
                                        fontWeight: FontWeight.w400)),
                                Assets.images.iconMemberVipMore
                                    .image(width: 16.w, height: 16.w)
                              ],
                            )),
                      ],
                    ),
                  ),
                ));
          })
        ],
      ),
    );
  }

  Widget buildMemberCardVipDesc() {
    return Obx(() {
      String desc = '';
      if (!controller.isLogin) {
        desc = StringName.memberCardNoLoginDesc;
      } else if (controller.memberStatusInfo == null ||
          controller.memberStatusInfo?.expired == true) {
        desc = StringName.memberCardNoVipDesc;
      } else if (controller.memberStatusInfo?.expired == false &&
          controller.memberStatusInfo?.permanent == true) {
        desc = StringName.memberCardPermanentVipDesc;
      } else {
        desc =
            '${DateUtil.fromMillisecondsSinceEpoch('yyyy.MM.dd', controller.memberStatusInfo?.endTimestamp ?? 0)} ${StringName.memberCardExpirationDesc}';
      }
      return Text(desc,
          style: TextStyle(fontSize: 12.sp, color: ColorName.white80));
    });
  }

  Widget buildBuyMemberCardBtn() {
    return Obx(() {
      String txt = "";
      if (!controller.isLogin ||
          controller.memberStatusInfo == null ||
          controller.memberStatusInfo?.expired == true) {
        txt = StringName.memberVipUnlock;
      } else if (controller.memberStatusInfo?.expired == false &&
          controller.memberStatusInfo?.permanent == true) {
        txt = StringName.mineMemberPermanent;
      } else {
        txt = StringName.memberVipRenew;
      }
      return Container(
        margin: EdgeInsets.only(right: 20.w),
        decoration: BoxDecoration(
            color: ColorName.white, borderRadius: BorderRadius.circular(26.w)),
        padding: EdgeInsets.symmetric(horizontal: 13.w, vertical: 6.w),
        child: Text(txt,
            style: TextStyle(
                fontSize: 12.sp,
                color: '#5558FC'.color,
                fontWeight: FontWeight.bold)),
      );
    });
  }

  Widget buildFunList() {
    return Container(
      decoration: BoxDecoration(
          color: ColorName.white, borderRadius: BorderRadius.circular(12.w)),
      margin: EdgeInsets.symmetric(horizontal: 12.w),
      padding: EdgeInsets.symmetric(vertical: 5.w),
      child: Column(
        children: [
          buildMineFunItem(
              Assets.images.iconMineUrgentContact.provider(),
              StringName.mineUrgentContact,
              () => controller.onUrgentContactClick()),
          buildMineFunItem(Assets.images.iconMineFunShare.provider(),
              StringName.mineFunShare, () => controller.onShareClick()),
          Visibility(
            visible: Platform.isAndroid,
            child: buildMineFunItem(
                Assets.images.iconMineFunCustomerService.provider(),
                StringName.mineFunCustomerService,
                () => controller.onCustomerServiceClick()),
          ),
          buildMineFunItem(
              Assets.images.iconMineFunPermissionSetting.provider(),
              StringName.mineFunPermissionSetting,
              () => controller.onPermissionSettingClick()),
          if (Platform.isAndroid)
            buildMineFunItem(
                Assets.images.iconMineFunAccountFeedback.provider(),
                StringName.mineFunAccountFeedback,
                () => controller.onAccountFeedbackClick()),
          buildMineFunItem(Assets.images.iconMineFunAbout.provider(),
              StringName.mineFunAbout, () => controller.onAboutClick()),
          Obx(() {
            return Visibility(
              visible: controller.isLogin,
              child: buildMineFunItem(
                  Assets.images.iconMineFunLogoutAccount.provider(),
                  StringName.mineFunLogoutAccount,
                  () => controller.onLogoutAccountClick()),
            );
          }),
          Obx(() {
            return Visibility(
              visible: controller.isLogin,
              child: buildMineFunItem(
                  Assets.images.iconMineFunExitAccount.provider(),
                  StringName.mineFunExitAccount,
                  () => controller.onFunExitAccountClick()),
            );
          }),
        ],
      ),
    );
  }

  Widget buildAvatarView(String avatar) {
    return Container(
      decoration: BoxDecoration(
        shape: BoxShape.circle,
        border: Border.all(
          color: '#E8E1FF'.color,
          width: 1.w,
        ),
      ),
      child: buildCustomAvatarView(
        size: 54.w,
        avatar: avatar,
      ),
    );
  }
}
