import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:yumi/app_localizations.dart';
import 'package:yumi/ui_kit/components/sc_debounce_widget.dart';
import 'package:yumi/shared/tools/sc_loading_manager.dart';
import 'package:yumi/shared/data_sources/sources/local/user_manager.dart';
import 'package:yumi/shared/data_sources/sources/repositories/sc_user_repository_impl.dart';
import 'package:yumi/services/auth/user_profile_manager.dart';
import 'package:yumi/main.dart';
import 'package:provider/provider.dart';
import 'package:yumi/ui_kit/components/appbar/socialchat_appbar.dart';
import 'package:yumi/ui_kit/components/sc_compontent.dart';
import 'package:yumi/ui_kit/components/text/sc_text.dart';
import 'package:yumi/ui_kit/components/sc_tts.dart';
import 'package:yumi/app/routes/sc_fluro_navigator.dart';
import 'package:yumi/shared/tools/sc_lk_dialog_util.dart';
import 'package:yumi/services/general/sc_app_general_manager.dart';
import 'package:yumi/services/audio/rtc_manager.dart';
import 'package:yumi/ui_kit/theme/socialchat_theme.dart';
import '../../../shared/tools/sc_pick_utils.dart';
import '../../../shared/business_logic/models/res/country_res.dart';
import '../../../shared/business_logic/usecases/sc_accurate_length_limiting_textInput_formatter.dart';
import '../../country/country_route.dart';

class EditUserInfoPage2 extends StatefulWidget {
  const EditUserInfoPage2({Key? key}) : super(key: key);

  @override
  _EditUserInfoPage2State createState() => _EditUserInfoPage2State();
}

class _EditUserInfoPage2State extends State<EditUserInfoPage2>
    with SingleTickerProviderStateMixin {
  String? userCover;

  String? bornMonth;
  String? autograph;
  String? hobby;
  String? bornDay;
  String? bornYear;
  String nickName = "";
  DateTime? birthdayDate;
  num? sex;
  num? age;
  Country? country;

  @override
  void initState() {
    super.initState();
    userCover =
        AccountStorage().getCurrentUser()?.userProfile?.userAvatar ?? "";
    nickName =
        AccountStorage().getCurrentUser()?.userProfile?.userNickname ?? "";
    autograph = AccountStorage().getCurrentUser()?.userProfile?.autograph ?? "";
    hobby = AccountStorage().getCurrentUser()?.userProfile?.hobby ?? "";
    country = Provider.of<SCAppGeneralManager>(
      context,
      listen: false,
    ).findCountryByName(
      AccountStorage().getCurrentUser()?.userProfile?.countryName ?? "",
    );
    num m = AccountStorage().getCurrentUser()?.userProfile?.bornMonth ?? 0;
    if (m < 10) {
      bornMonth = "0$m";
    } else {
      bornMonth = "$m";
    }
    num d = AccountStorage().getCurrentUser()?.userProfile?.bornDay ?? 0;
    if (d < 10) {
      bornDay = "0$d";
    } else {
      bornDay = "$d";
    }
    bornYear = "${AccountStorage().getCurrentUser()?.userProfile?.bornYear}";
    age =
        DateTime.now().year -
        (AccountStorage().getCurrentUser()?.userProfile?.bornYear ?? 0);
    sex = AccountStorage().getCurrentUser()?.userProfile?.userSex;
  }

  @override
  void dispose() {
    super.dispose();
  }

  String? _preferNonEmpty(String? primary, String? fallback) {
    if ((primary ?? "").trim().isNotEmpty) {
      return primary;
    }
    if ((fallback ?? "").trim().isNotEmpty) {
      return fallback;
    }
    return primary ?? fallback;
  }

  bool _isBrokenLocalMediaUrl(String? url) {
    return (url ?? "").contains("/external/oss/local/");
  }

  String? _preferUsableAvatar(String? primary, String? fallback) {
    if ((primary ?? "").trim().isNotEmpty && !_isBrokenLocalMediaUrl(primary)) {
      return primary;
    }
    if ((fallback ?? "").trim().isNotEmpty &&
        !_isBrokenLocalMediaUrl(fallback)) {
      return fallback;
    }
    return _preferNonEmpty(primary, fallback);
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Image.asset(
          "sc_images/person/sc_icon_edit_userinfo_bg.png",
          width: ScreenUtil().screenWidth,
          height: ScreenUtil().screenHeight,
          fit: BoxFit.fill,
        ),
        Scaffold(
          backgroundColor: Colors.transparent,
          resizeToAvoidBottomInset: true,
          appBar: SocialChatStandardAppBar(
            title: SCAppLocalizations.of(context)!.editProfile,
            actions: [],
          ),
          body: Consumer<SocialChatUserProfileManager>(
            builder: (context, ref, child) {
              return Column(
                spacing: 10.w,
                children: [
                  SCDebounceWidget(
                    child: Row(
                      children: [
                        SizedBox(width: 15.w),
                        text(
                          SCAppLocalizations.of(context)!.profilePhoto,
                          textColor: Colors.white,
                          fontSize: 15.sp,
                          fontWeight: FontWeight.w600,
                        ),
                        Spacer(),
                        Stack(
                          alignment: AlignmentDirectional.bottomEnd,
                          children: [
                            netImage(
                              url:
                                  _preferNonEmpty(
                                    userCover,
                                    UserManager()
                                        .getCurrentUser()
                                        ?.userProfile
                                        ?.userAvatar,
                                  ) ??
                                  "",
                              width: 45.w,
                              height: 45.w,
                              shape: BoxShape.circle,
                            ),
                          ],
                        ),
                        Icon(
                          Icons.keyboard_arrow_right,
                          size: 20.w,
                          color: Colors.white70,
                        ),
                        SizedBox(width: 8.w),
                      ],
                    ),
                    onTap: () {
                      SCPickUtils.pickImage(context, (
                        bool success,
                        String url,
                      ) {
                        if (success) {
                          debugPrint("[Profile Avatar] uploaded url: $url");
                          userCover = url;
                          setState(() {});
                          submitAvatarOnly(context);
                        }
                      });
                    },
                  ),
                  SizedBox(height: 3.w),
                  _buildItem(
                    "${SCAppLocalizations.of(context)!.userName}:",
                    nickName,
                    () {
                      _showInputBioHobby(nickName, 3);
                    },
                  ),
                  _buildItem(
                    "${SCAppLocalizations.of(context)!.gender}:",
                    sex == 1
                        ? SCAppLocalizations.of(context)!.man
                        : SCAppLocalizations.of(context)!.woman,
                    () {
                      _showSexDialog();
                    },
                  ),

                  _buildItem(
                    "${SCAppLocalizations.of(context)!.birthday}:",
                    "$bornYear-$bornMonth-$bornDay",
                    () {
                      _selectDate();
                    },
                  ),
                  _buildControlItem(),

                  _buildItem(
                    "${SCAppLocalizations.of(context)!.bio}:",
                    autograph ?? "",
                    () {
                      _showInputBioHobby(autograph ?? "", 1);
                    },
                  ),

                  _buildItem(
                    "${SCAppLocalizations.of(context)!.hobby}:",
                    hobby ?? "",
                    () {
                      _showInputBioHobby(hobby ?? "", 2);
                    },
                  ),
                ],
              );
            },
          ),
        ),
      ],
    );
  }

  Future<void> _selectDate() async {
    SmartDialog.show(
      tag: "showSelectDate",
      alignment: Alignment.bottomCenter,
      animationType: SmartAnimationType.fade,
      onDismiss: () {
        submit(context);
      },
      builder: (_) {
        return SafeArea(
          top: false,
          child: Container(
            height: 240.w,
            padding: EdgeInsets.only(top: 6),
            color: CupertinoColors.systemBackground,
            child: Column(
              children: [
                SizedBox(height: 10.w),
                Row(
                  children: [
                    SizedBox(width: 10.w),
                    GestureDetector(
                      child: Container(
                        alignment: Alignment.topCenter,
                        child: text(
                          SCAppLocalizations.of(context)!.cancel,
                          textColor: Colors.black87,
                          fontSize: 15.sp,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                      onTap: () {
                        SmartDialog.dismiss(tag: "showSelectDate");
                      },
                    ),
                    Expanded(
                      child: Container(
                        alignment: Alignment.topCenter,
                        child: text(
                          SCAppLocalizations.of(context)!.birthday,
                          textColor: Colors.black87,
                          fontSize: 15.sp,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    ),
                    GestureDetector(
                      child: Container(
                        alignment: Alignment.topCenter,
                        child: text(
                          SCAppLocalizations.of(context)!.confirm,
                          textColor: Color(0xff7726FF),
                          fontSize: 15.sp,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                      onTap: () {
                        num m = birthdayDate!.month;
                        if (m < 10) {
                          bornMonth = "0$m";
                        } else {
                          bornMonth = "$m";
                        }
                        num d = birthdayDate!.day;
                        if (d < 10) {
                          bornDay = "0$d";
                        } else {
                          bornDay = "$d";
                        }
                        bornYear = "${birthdayDate?.year}";
                        setState(() {});
                        SmartDialog.dismiss(tag: "showSelectDate");
                      },
                    ),
                    SizedBox(width: 10.w),
                  ],
                ),
                Expanded(
                  child: CupertinoDatePicker(
                    mode: CupertinoDatePickerMode.date,
                    initialDateTime: _getBefor18(),
                    maximumDate: _getBefor18(),
                    onDateTimeChanged: (date) {
                      birthdayDate = date;
                      age = DateTime.now().year - date.year;
                    },
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  DateTime _getBefor18() {
    DateTime currentDate = DateTime.now();
    DateTime eighteenYearsAgo = DateTime(
      currentDate.year - 18,
      currentDate.month,
      currentDate.day,
      currentDate.hour,
      currentDate.minute,
      currentDate.second,
      currentDate.millisecond,
      currentDate.microsecond,
    );
    return eighteenYearsAgo;
  }

  int sTime = 0;

  void submitAvatarOnly(BuildContext context) async {
    if ((userCover ?? "").trim().isEmpty) {
      return;
    }
    int bTime = DateTime.now().millisecondsSinceEpoch;
    if (bTime - sTime <= 5000) {
      return;
    }
    sTime = bTime;
    SCLoadingManager.show();
    debugPrint("[Profile Avatar] submit avatar only: {userAvatar: $userCover}");
    try {
      final updatedProfile = await SCAccountRepository().updateUserInfo(
        userAvatar: userCover,
      );
      final mergedProfile = updatedProfile.copyWith(
        userAvatar: _preferUsableAvatar(updatedProfile.userAvatar, userCover),
      );
      debugPrint(
        "[Profile Avatar] merged avatar-only profile avatar: ${mergedProfile.userAvatar ?? ""}",
      );
      userCover = mergedProfile.userAvatar;
      if (!mounted) {
        SCLoadingManager.hide();
        return;
      }
      Provider.of<SocialChatUserProfileManager>(
        context,
        listen: false,
      ).syncCurrentUserProfile(mergedProfile);
      Provider.of<RtcProvider>(context, listen: false).needUpDataUserInfo =
          true;
      SCTts.show(SCAppLocalizations.of(context)!.operationSuccessful);
    } catch (e) {
      debugPrint(e.toString());
      SCLoadingManager.hide();
      return;
    }
    SCLoadingManager.hide();
    if (mounted) {
      setState(() {});
    }
  }

  void submit(BuildContext context) async {
    if (nickName.isEmpty) {
      SCTts.show(SCAppLocalizations.of(context)!.pleaseEnterNickname);
      return;
    }
    int bTime = DateTime.now().millisecondsSinceEpoch;
    if (bTime - sTime > 5000) {
      sTime = bTime;
      SCLoadingManager.show();
      debugPrint(
        "[Profile Avatar] submit payload: {userAvatar: $userCover, userNickname: $nickName, userSex: $sex, age: $age, bornYear: ${birthdayDate?.year}, bornMonth: ${birthdayDate?.month}, bornDay: ${birthdayDate?.day}, countryId: ${country?.id}, hobby: $hobby, autograph: $autograph}",
      );
      try {
        final updatedProfile = await SCAccountRepository().updateUserInfo(
          userAvatar: userCover,
          userSex: sex,
          userNickname: nickName,
          age: age,
          bornDay: birthdayDate?.day,
          bornMonth: birthdayDate?.month,
          bornYear: birthdayDate?.year,
          hobby: hobby,
          autograph: autograph,
          countryId: country?.id,
        );
        final mergedProfile = updatedProfile.copyWith(
          userAvatar: _preferUsableAvatar(updatedProfile.userAvatar, userCover),
          userNickname: _preferNonEmpty(updatedProfile.userNickname, nickName),
          autograph: _preferNonEmpty(updatedProfile.autograph, autograph),
          hobby: _preferNonEmpty(updatedProfile.hobby, hobby),
          countryName: _preferNonEmpty(
            updatedProfile.countryName,
            country?.countryName,
          ),
          countryCode: _preferNonEmpty(
            updatedProfile.countryCode,
            country?.alphaTwo,
          ),
          countryId: _preferNonEmpty(updatedProfile.countryId, country?.id),
          userSex: updatedProfile.userSex ?? sex,
          age: updatedProfile.age ?? age,
          bornDay: updatedProfile.bornDay ?? birthdayDate?.day,
          bornMonth: updatedProfile.bornMonth ?? birthdayDate?.month,
          bornYear: updatedProfile.bornYear ?? birthdayDate?.year,
        );
        debugPrint(
          "[Profile Avatar] merged profile avatar: ${mergedProfile.userAvatar ?? ""}",
        );
        userCover = mergedProfile.userAvatar;
        if (!mounted) {
          SCLoadingManager.hide();
          return;
        }
        Provider.of<SocialChatUserProfileManager>(
          context,
          listen: false,
        ).syncCurrentUserProfile(mergedProfile);
        Provider.of<RtcProvider>(context, listen: false).needUpDataUserInfo =
            true;
        SCTts.show(SCAppLocalizations.of(context)!.operationSuccessful);
      } catch (e) {
        debugPrint(e.toString());
        SCLoadingManager.hide();
        return;
      }
      SCLoadingManager.hide();
      if (mounted) {
        setState(() {});
      }
    }
  }

  void _showSexDialog() {
    showCenterDialog(
      context,
      Container(
        height: 150.w,
        width: ScreenUtil().screenWidth * 0.7,
        decoration: BoxDecoration(
          color: Color(0xff09372E),
          borderRadius: BorderRadius.all(Radius.circular(12)),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            SizedBox(height: 15.w),
            text(
              SCAppLocalizations.of(context)!.pleaseSelectYourGender,
              fontSize: 15.sp,
              textColor: Colors.white,
            ),
            SizedBox(height: 5.w),
            Divider(color: Colors.black12, thickness: 0.5, height: 14.w),
            SizedBox(height: 8.w),
            GestureDetector(
              onTap: () {
                sex = 1;
                setState(() {});
                submit(context);
                SCNavigatorUtils.goBack(context);
              },
              behavior: HitTestBehavior.opaque,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                mainAxisSize: MainAxisSize.max,
                children: [
                  xb(1, color: Colors.white, height: 18.w),
                  SizedBox(width: 5.w),
                  text(
                    SCAppLocalizations.of(context)!.man,
                    textColor: Colors.white,
                    fontSize: 15.sp,
                  ),
                ],
              ),
            ),
            SizedBox(height: 8.w),
            Divider(color: Colors.black12, thickness: 0.5, height: 14.w),
            SizedBox(height: 8.w),
            GestureDetector(
              onTap: () {
                sex = 0;
                setState(() {});
                submit(context);
                SCNavigatorUtils.goBack(context);
              },
              behavior: HitTestBehavior.opaque,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                mainAxisSize: MainAxisSize.max,
                children: [
                  xb(0, color: Colors.white, height: 18.w),
                  SizedBox(width: 5.w),
                  text(
                    SCAppLocalizations.of(context)!.woman,
                    textColor: Colors.white,
                    fontSize: 15.sp,
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  _buildItem(String title, String value, Function() func) {
    return SCDebounceWidget(
      child: Column(
        children: [
          Row(
            children: [
              SizedBox(width: 15.w),
              text(
                title,
                textColor: Colors.white,
                fontSize: 15.sp,
                fontWeight: FontWeight.w600,
              ),
              Expanded(
                child: Container(
                  alignment: AlignmentDirectional.centerEnd,
                  child: text(value, textColor: Colors.white, fontSize: 15.sp),
                ),
              ),
              Icon(
                Icons.keyboard_arrow_right,
                size: 20.w,
                color: Colors.white70,
              ),
              SizedBox(width: 8.w),
            ],
          ),
          SizedBox(height: 8.w),
          Container(
            margin: EdgeInsets.only(left: 15.w, right: 15.w),
            color: Colors.white12,
            height: 0.5.w,
            width: ScreenUtil().screenWidth,
          ),
        ],
      ),
      onTap: () {
        func.call();
      },
    );
  }

  _buildControlItem() {
    return SCDebounceWidget(
      child: Column(
        children: [
          Row(
            children: [
              SizedBox(width: 15.w),
              text(
                SCAppLocalizations.of(context)!.country,
                textColor: Colors.white,
                fontSize: 15.sp,
                fontWeight: FontWeight.w600,
              ),
              Spacer(),
              Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  netImage(
                    url: country?.nationalFlag ?? "",
                    width: 26.w,
                    height: 16.w,
                    borderRadius: BorderRadius.all(Radius.circular(2.w)),
                  ),
                  SizedBox(width: 5.w),
                  text(
                    country?.countryName ?? "",
                    textColor: Colors.white,
                    fontSize: 15.sp,
                  ),
                ],
              ),
              Icon(
                Icons.keyboard_arrow_right,
                size: 20.w,
                color: Colors.white70,
              ),
              SizedBox(width: 8.w),
            ],
          ),
          SizedBox(height: 8.w),
          Container(
            margin: EdgeInsets.only(left: 15.w, right: 15.w),
            color: Colors.white12,
            height: 0.5.w,
            width: ScreenUtil().screenWidth,
          ),
        ],
      ),
      onTap: () {
        SCNavigatorUtils.push(
          context,
          CountryRoute.country,
          replace: false,
        ).then((res) {
          var c =
              Provider.of<SCAppGeneralManager>(
                navigatorKey.currentState!.context,
                listen: false,
              ).selectCountryInfo;
          if (c != null) {
            country = c;
            submit(navigatorKey.currentState!.context);
            setState(() {});
          }
        });
      },
    );
  }

  void _showInputBioHobby(String content, int type) {
    SmartDialog.dismiss(tag: "showInputBioHobby");
    TextEditingController _inputController = TextEditingController();
    _inputController.text = content;
    SmartDialog.show(
      tag: "showInputBioHobby",
      alignment: Alignment.center,
      debounce: true,
      animationType: SmartAnimationType.fade,
      builder: (_) {
        return Container(
          height: 250.w,
          margin: EdgeInsets.symmetric(horizontal: 20.w),
          decoration: BoxDecoration(
            color: Color(0xff09372E),
            borderRadius: BorderRadius.circular(10.w),
          ),
          child: Column(
            children: [
              SizedBox(height: 8.w),
              Row(
                children: [
                  SizedBox(width: 10.w),
                  GestureDetector(
                    child: Icon(Icons.close, color: Colors.white, size: 20.w),
                    onTap: () {
                      SmartDialog.dismiss(tag: "showInputBioHobby");
                    },
                  ),
                  Spacer(),
                  text(
                    SCAppLocalizations.of(context)!.pleaseEnterContent,
                    textColor: Colors.white,
                    fontSize: 15.sp,
                  ),
                  Spacer(),
                  SizedBox(width: 20.w),
                ],
              ),
              SizedBox(height: 15.w),
              Container(
                margin: EdgeInsets.symmetric(horizontal: 25.w),
                padding: EdgeInsets.only(top: 5.w, left: 12.w, right: 12.w),
                alignment: AlignmentDirectional.centerStart,
                height: 110.w,
                width: ScreenUtil().screenWidth,
                decoration: BoxDecoration(
                  color: Colors.black26,
                  borderRadius: BorderRadius.all(Radius.circular(8.w)),
                  border: Border.all(color: Color(0xffE6E6E6), width: 0.5.w),
                ),
                child: TextField(
                  controller: _inputController,
                  maxLines: 5,
                  inputFormatters: [
                    SCAccurateLengthLimitingTextInputFormatter(50),
                  ],
                  decoration: InputDecoration(
                    isDense: true,
                    hintText: "",
                    hintStyle: TextStyle(color: Colors.white, fontSize: 14.sp),
                    contentPadding: EdgeInsets.only(top: 0.w),
                    counterText: '',
                    filled: false,
                    focusColor: Colors.transparent,
                    hoverColor: Colors.transparent,
                    border: InputBorder.none,
                    enabledBorder: InputBorder.none,
                    focusedBorder: InputBorder.none,
                    disabledBorder: InputBorder.none,
                    errorBorder: InputBorder.none,
                    focusedErrorBorder: InputBorder.none,
                    // enabledBorder: UnderlineInputBorder(
                    //   borderSide: BorderSide(width: 0.5,color: Colors.white,style: BorderStyle.solid),),
                    // focusedBorder: UnderlineInputBorder(
                    //   borderSide: BorderSide(width: 0.5,color: Colors.white,style: BorderStyle.solid),),
                    // prefixIcon: Padding(padding: EdgeInsets.all(8.w), child: Image.asset("images/login/sc_icon_phone.png",width: 20.w, height: 20.w,fit: BoxFit.fill,),),
                    fillColor: Colors.white54,
                  ),
                  style: TextStyle(
                    fontSize: 15.w,
                    color: Colors.white,
                    textBaseline: TextBaseline.alphabetic,
                  ),
                ),
              ),
              SizedBox(height: 15.w),
              SCDebounceWidget(
                child: Container(
                  alignment: Alignment.center,
                  margin: EdgeInsets.symmetric(horizontal: 60.w),
                  height: 42.w,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(20.w),
                    color: SocialChatTheme.primaryLight,
                  ),
                  child: text(
                    SCAppLocalizations.of(context)!.confirm,
                    textColor: Colors.white,
                    fontSize: 16.sp,
                    fontWeight: FontWeight.w600,
                  ),
                ),
                onTap: () {
                  SmartDialog.dismiss(tag: "showInputBioHobby");
                  if (type == 1) {
                    autograph = _inputController.text;
                    setState(() {});
                  } else if (type == 2) {
                    hobby = _inputController.text;
                    setState(() {});
                  } else if (type == 3) {
                    nickName = _inputController.text;
                    setState(() {});
                  }
                  submit(navigatorKey.currentState!.context);
                },
              ),
            ],
          ),
        );
      },
    );
  }
}
