import 'package:app_settings/app_settings.dart';
import 'package:auto_route/auto_route.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:page_transition/page_transition.dart';
import 'package:provider/provider.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:telnow_mobile_new/src/api/api_auth_provider.dart';
import 'package:telnow_mobile_new/src/layouts/functions/account.dart';
import 'package:telnow_mobile_new/src/layouts/mobile/password.dart';
import 'package:telnow_mobile_new/src/layouts/components/template.dart';
import 'package:telnow_mobile_new/src/utils/U.dart';
import 'package:telnow_mobile_new/src/utils/provider.dart';
import 'package:permission_handler/permission_handler.dart';

class MobAccountPage extends StatefulWidget {
  const MobAccountPage({super.key});

  @override
  State<MobAccountPage> createState() => _MobAccountPageState();
}

class _MobAccountPageState extends State<MobAccountPage> {
  final AccountFunction accFunc = AccountFunction();
  
  bool isDeniedNotifPermission = false;
  bool serDis = false;
  bool dnd = false;
  bool autoTranslate = false;
  List lang = [];
  bool _timeLimit = false;

  @override
  void initState() {
    Provider.of<UserModule>(context, listen: false).reset();

    accFunc.getUser(context);
    setToggle();
    checkPermission(0);

    // TODO: implement initState
    super.initState();
  }

  checkPermission(seconds){
    Future.delayed(Duration(seconds: seconds)).then((value)async {
      bool denied = await Permission.notification.isDenied;
      if(!U.getNotifPermission() && !denied) U.setNotifPermissionDismissed(false);

      U.setNotifPermission(!denied);
      setState(() => isDeniedNotifPermission = denied);
    });
  }

  setToggle() async{
    var license = await U.getLicense();
    setState(() {
      dnd = Provider.of<UserModule>(context, listen: false).dndStatus();
      serDis = U.servantDisplay();
      autoTranslate = U.autoTranslate();
      lang = license['languages'] != null ? license['languages'].split(',') : [];
    });
  }

  @override
  Widget build(BuildContext context) {
    var codeOflang = {
      "id": 'bahasa'.tr(),
      "en": 'english'.tr(),
      "ja": 'japanese'.tr(),
      "zh": 'chinese'.tr(),
      "ko": 'korean'.tr(),
      "ar": 'العربية'
    };
    return Provider.of<UserModule>(context).user().isNotEmpty ? Scaffold(
      backgroundColor: backgroundColor,
      appBar: AppBar(
        elevation: 0,
        bottomOpacity: 0,
        backgroundColor: backgroundColor,
        titleSpacing: 16,
        title: Text('account'.tr(), style: TextStyle(color: textColor, fontSize: 17, fontWeight: FontWeight.w500), overflow: TextOverflow.ellipsis),
      ),
      body: Column(
        children: [
          divider(),
          Expanded(
            child: Container(
              alignment: Alignment.topCenter,
              width: U.bodyWidth(context),
              child: SingleChildScrollView(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Container(
                      padding: EdgeInsets.all(16),
                      child: Row(
                        children: [
                          CircleAvatar(
                            child: Text(Provider.of<UserModule>(context).user()['name'][0].toString().toUpperCase(), style: TextStyle(color: Colors.white)),
                            backgroundColor: primaryColor,
                            radius: 25,
                          ),
                          SizedBox(width: 16),
                          Expanded(child: Text(Provider.of<UserModule>(context).user()['name'], style: TextStyle(fontSize: 16, fontWeight: FontWeight.w500, color: textColor), maxLines: 2, overflow: TextOverflow.ellipsis))
                        ],
                      ),
                    ),
                    separator(),
                    Container(
                      padding: EdgeInsets.all(16),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text('info_label'.tr(), style: TextStyle(color: textColor, fontSize: 16, fontWeight: FontWeight.w500)),
                          SizedBox(height: 20),
                          textHorizontal('userId'.tr(), Provider.of<UserModule>(context).user()['relatedTo'] != null ? Provider.of<UserModule>(context).user()['relatedTo'] : Provider.of<UserModule>(context).user()['userId'], size: 16, opacity: 0.75),
                          SizedBox(height: 12),
                          textHorizontal('location'.tr(), Provider.of<UserModule>(context).user()['location'] != null ? Provider.of<UserModule>(context).user()['location'] : '-', size: 16, opacity: 0.75),
                          SizedBox(height: 12),
                          textHorizontal('servantGroup'.tr(), Provider.of<UserModule>(context).user()['requestTypeListDescriptionMobile'] != null ? Provider.of<UserModule>(context).user()['requestTypeListDescriptionMobile'].toLowerCase() == 'semua' ? 'all'.tr() : Provider.of<UserModule>(context).user()['requestTypeListDescriptionMobile'] : '-', size: 16, opacity: 0.75),
                        ],
                      ),
                    ),
                    Provider.of<UserModule>(context).houseKeeping()?separator():Container(),
                    Provider.of<UserModule>(context).houseKeeping()?Container(
                      padding: EdgeInsets.all(16),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text('doNotDisturb'.tr(), style: TextStyle(color: textColor, fontSize: 16, fontWeight: FontWeight.w500)),
                          SizedBox(height: 20),
                          Row(
                            children: [
                              Expanded(child: Text('set_dnd_status'.tr(), style: TextStyle(color: textColor.withValues(alpha: 0.75), fontSize: 16))),
                              Text(dnd?'active_dnd'.tr():'inactive_dnd'.tr(), style: TextStyle(color: textColor, fontSize: 14)),
                              SizedBox(width: 5),
                              GestureDetector(
                                child: Container(
                                  decoration: BoxDecoration(border: Border.all(color: Provider.of<UserModule>(context).user()['checkedIn']?primaryColor:Colors.black38, width: 1.5), borderRadius: BorderRadius.all(Radius.circular(50))),
                                  child: Row(
                                    children: [
                                      !dnd?Container(
                                        width: 20, height: 20, decoration: BoxDecoration(color: Provider.of<UserModule>(context).user()['checkedIn']?primaryColor:Colors.black38, borderRadius: BorderRadius.all(Radius.circular(20))),
                                      ):Container(width: 20, height: 20),
                                      dnd?Container(
                                        width: 20, height: 20, decoration: BoxDecoration(color: Provider.of<UserModule>(context).user()['checkedIn']?primaryColor:Colors.black38, borderRadius: BorderRadius.all(Radius.circular(20))),
                                      ):Container(width: 20, height: 20),
                                    ],
                                  ),
                                ),
                                onTap: Provider.of<UserModule>(context).user()['checkedIn']?(){
                                  dialogConfirm(context: context, title: 'set_dnd_status'.tr(), text: dnd?'msg_change_inactive'.tr():'msg_change_active'.tr(), actionYes: ()async{
                                    bool res = await accFunc.setDndStatus(context, dnd);
                                    if(res){
                                      setState(() => dnd = !dnd);
                                    }
                                  });
                                }:null,
                              ),
                            ],
                          )
                        ],
                      ),
                    ):Container(),
                    !Provider.of<UserModule>(context).user()['_profile']['isRoom']?separator():Container(),
                    !Provider.of<UserModule>(context).user()['_profile']['isRoom']?Container(
                      padding: EdgeInsets.all(16),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text('display_menu'.tr(), style: TextStyle(color: textColor, fontSize: 16, fontWeight: FontWeight.w500)),
                          SizedBox(height: 20),
                          Row(
                            children: [
                              Expanded(child: Text(serDis?'ser_group'.tr():'req_group'.tr(), style: TextStyle(color: textColor.withValues(alpha: 0.75), fontSize: 16))),
                              SizedBox(width: 5),
                              GestureDetector(
                                child: Container(
                                  decoration: BoxDecoration(border: Border.all(color: primaryColor, width: 1.5), borderRadius: BorderRadius.all(Radius.circular(50))),
                                  child: Row(
                                    children: [
                                      !serDis?Container(
                                        width: 20, height: 20, decoration: BoxDecoration(color: primaryColor, borderRadius: BorderRadius.all(Radius.circular(20))),
                                      ):Container(width: 20, height: 20),
                                      serDis?Container(
                                        width: 20, height: 20, decoration: BoxDecoration(color: primaryColor, borderRadius: BorderRadius.all(Radius.circular(20))),
                                      ):Container(width: 20, height: 20),
                                    ],
                                  ),
                                ),
                                onTap: (){
                                  setState(() {
                                    if(serDis){
                                      U.setServantDisplay(false);
                                      serDis = false;
                                    }
                                    else{
                                      U.setServantDisplay(true);
                                      serDis = true;
                                    }
                                  });
                                },
                              ),
                            ],
                          )
                        ],
                      ),
                    ):Container(),

                    separator(),
                    Container(
                      padding: EdgeInsets.fromLTRB(16, 16, 16, 0),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text('setting'.tr(), style: TextStyle(color: textColor, fontSize: 16, fontWeight: FontWeight.w500)),
                          SizedBox(height: 6),
                          GestureDetector(
                            child: Container(
                              color: Colors.white,
                              padding: EdgeInsets.symmetric(vertical: 16),
                              child: Row(
                                children: [
                                  U.iconsax('bold/global', color: textColor.withValues(alpha: 0.75)),
                                  SizedBox(width: 16),
                                  Expanded(child: Text('language'.tr(), style: TextStyle(color: textColor.withValues(alpha: 0.75), fontSize: 16), overflow: TextOverflow.ellipsis)),
                                  Text(codeOflang[context.locale.toString()]!, style: TextStyle(color: textColor)),
                                  SizedBox(width: 12),
                                  U.iconsax('arrow-right-3', size: 16, color: textColor.withValues(alpha: 0.75)),
                                ],
                              ),
                            ),
                            onTap: ()=>changeLang(context, Provider.of<UserModule>(context, listen: false).user()),
                          ),
                          divider(),
                          Container(
                            color: Colors.white,
                            padding: EdgeInsets.symmetric(vertical: 16),
                            child: Row(
                              children: [
                                Icon(Icons.g_translate_rounded, color: textColor.withValues(alpha: 0.75)),
                                SizedBox(width: 16),
                                Expanded(child: Text('auto_translate'.tr(), style: TextStyle(color: textColor.withValues(alpha: 0.75), fontSize: 16), overflow: TextOverflow.ellipsis)),
                                Text(autoTranslate?'ON':'OFF', style: TextStyle(color: textColor)),
                                SizedBox(width: 5),
                                GestureDetector(
                                  child: Container(
                                    decoration: BoxDecoration(border: Border.all(color: autoTranslate?primaryColor:Colors.black38, width: 1.5), borderRadius: BorderRadius.all(Radius.circular(50))),
                                    child: Row(
                                      children: [
                                        !autoTranslate?Container(
                                          width: 20, height: 20, decoration: BoxDecoration(color: Colors.black38, borderRadius: BorderRadius.all(Radius.circular(20))),
                                        ):Container(width: 20, height: 20),
                                        autoTranslate?Container(
                                          width: 20, height: 20, decoration: BoxDecoration(color: primaryColor, borderRadius: BorderRadius.all(Radius.circular(20))),
                                        ):Container(width: 20, height: 20),
                                      ],
                                    ),
                                  ),
                                  onTap: (){
                                    setState(() {
                                      if(autoTranslate){
                                        U.setAutoTranslate(false);
                                        autoTranslate = false;
                                      }
                                      else{
                                        U.setAutoTranslate(true);
                                        autoTranslate = true;
                                      }
                                    });
                                  },
                                ),
                              ],
                            ),
                          ),
                          divider(),
                          GestureDetector(
                            child: Container(
                              color: Colors.white,
                              padding: EdgeInsets.symmetric(vertical: 16),
                              child: Row(
                                children: [
                                  U.iconsax('bold/key', color: textColor.withValues(alpha: 0.75)),
                                  SizedBox(width: 16),
                                  Text('password'.tr(), style: TextStyle(color: textColor.withValues(alpha: 0.75), fontSize: 16)),
                                  Expanded(child: Text('settingPasswordText'.tr(), style: TextStyle(color: textColor), overflow: TextOverflow.ellipsis, textAlign: TextAlign.end)),
                                  SizedBox(width: 12),
                                  U.iconsax('arrow-right-3', size: 16, color: textColor.withValues(alpha: 0.75)),
                                ],
                              ),
                            ),
                            onTap: ()=>Navigator.push(context, PageTransition(type: PageTransitionType.rightToLeft, child: MobPasswordPage(user: Provider.of<UserModule>(context, listen: false).user()))).then((value) {
                              value??false;
                              if (value) showSuccess(context, 'messagePassChanged'.tr());
                            }),
                          ),
                          divider(),
                          GestureDetector(
                            child: Container(
                              color: Colors.white,
                              padding: EdgeInsets.symmetric(vertical: 16),
                              child: Row(
                                children: [
                                  U.iconsax('bold/logout', color: textColor.withValues(alpha: 0.75)),
                                  SizedBox(width: 16),
                                  Expanded(child: Text('logout'.tr(), style: TextStyle(color: textColor.withValues(alpha: 0.75), fontSize: 16), overflow: TextOverflow.ellipsis)),
                                  U.iconsax('arrow-right-3', size: 16, color: textColor.withValues(alpha: 0.75)),
                                ],
                              ),
                            ),
                            onTap: (){
                              showDialog(
                                context: context,
                                builder: (BuildContext context) {
                                  return AlertDialog(
                                    title: Text("logout".tr()),
                                    content: Text("textLogout".tr()),
                                    actions: <Widget>[
                                      TextButton(
                                        child: Text("buttonNo".tr()),
                                        onPressed: () {
                                          Navigator.of(context).pop();
                                        },
                                      ),
                                      TextButton(
                                          onPressed: () => accFunc.logoutAction(context),
                                          child: Text("buttonYes".tr())),
                                    ],
                                  );
                                },
                              );
                            },
                          ),
                        ],
                      ),
                    ),
                    separator(),
                    GestureDetector(
                      child: Container(
                        color: Colors.white,
                        margin: EdgeInsets.symmetric(horizontal: 16),
                        padding: EdgeInsets.symmetric(vertical: 16),
                        child: Row(
                          children: [
                            U.iconsax('bold/scan', color: textColor.withValues(alpha: 0.75)),
                            SizedBox(width: 16),
                            Expanded(child: Text('scan_qr'.tr(), style: TextStyle(color: textColor.withValues(alpha: 0.75), fontSize: 16), overflow: TextOverflow.ellipsis)),
                            U.iconsax('arrow-right-3', size: 16, color: textColor.withValues(alpha: 0.75)),
                          ],
                        ),
                      ),
                      onTap: (){
                        var size = MediaQuery.of(context).size.width - (MediaQuery.of(context).size.width/3);
                        var pid = U.getPidFromUrl(context.router.currentUrl);
                        var qr_data = 'https://telnow.telmessenger.com/#/app/${pid}%23${U.getBaseUrl()}';
                        showDialog(
                          context: context,
                          builder: (BuildContext context) {
                            return AlertDialog(
                              title: Text("show_qr".tr(), style: TextStyle(fontSize: 16, color: Colors.black), textAlign: TextAlign.center),
                              content: Column(
                                mainAxisSize: MainAxisSize.min,
                                crossAxisAlignment: CrossAxisAlignment.center,
                                children: [
                                  SizedBox(
                                    width: size,
                                    height: size,
                                    child: QrImageView(
                                      data: qr_data,
                                      version: QrVersions.auto,
                                      gapless: true,
                                    ),
                                  ),
                                  SizedBox(height: 15),
                                  Text("show_qr_desc".tr(), style: TextStyle(fontSize: 14, color: Colors.black), textAlign: TextAlign.center)
                                ],
                              ),
                            );
                          },
                        );
                      },
                    ),
                    separator(),
                    isDeniedNotifPermission ? Container(
                      padding: EdgeInsets.all(16),
                      child: GestureDetector(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text("not_allow_permission".tr()),
                            SizedBox(height: 8,),
                            Text("tap_here".tr(), style: TextStyle(color: Color(0xFF198AF2)),),
                          ],
                        ),
                        onTap: () => AppSettings.openAppSettings(type: AppSettingsType.notification).then((value) async {
                          // print("after open setting");
                          // checkPermission(2);
                        }),
                      ),
                    ) : Container(),
                    isDeniedNotifPermission ? Container() : separator(),
                    Padding(
                      padding: const EdgeInsets.symmetric(vertical: 24),
                      child: Center(child: Column(
                        children: [
                          Text("${"version".tr()} ${ApiAuthProvider().displayVersion}"),
                          Text("Build ${ApiAuthProvider().buildNumber}", style: TextStyle(fontSize: 13),),
                        ],
                      )),
                    )
                  ],
                ),
              ),
            ),
          )
        ],
      ),
    ) : Provider.of<UserModule>(context).resetData() ? RefreshPage(() {
      Provider.of<UserModule>(context, listen: false).setResetData(false);
      accFunc.getUser(context);
    }) : _timeLimit ? showButton(context) : loadingTemplate(() {if(mounted) setState(()=>_timeLimit=true);},);
  }

  changeLang(context, user) {
    showModalBottomSheet(
        context: context,
        backgroundColor: Colors.white,
        builder: (BuildContext context) {
          return Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              Padding(
                padding: EdgeInsets.symmetric(vertical: 16),
                child: Center(
                  child: Text('chooseLanguage'.tr(), style: TextStyle(color: textColor)),
                ),
              ),
              divider(),
              SizedBox(height: 16),
              listOfLang(user),
              SizedBox(height: 16)
            ],
          );
        }
    );
  }

  listOfLang(user){
    return SafeArea(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          ListTile(
            title: Text('bahasa'.tr(), style: TextStyle(color: textColor, fontSize: 14)),
            trailing: Icon(context.locale.toString()=='id'?Icons.radio_button_checked:Icons.radio_button_off, color: primaryColor, size: 18),
            onTap: context.locale.toString() != 'id' ? () async {
              accFunc.switchLang(context, 'id', user);
            } : null,
          ),
          ListTile(
            title: Text('english'.tr(), style: TextStyle(color: textColor, fontSize: 14)),
            trailing: Icon(context.locale.toString()=='en'?Icons.radio_button_checked:Icons.radio_button_off, color: primaryColor, size: 18),
            onTap: context.locale.toString() != 'en' ? () async {
              accFunc.switchLang(context, 'en', user);
            } : null,
          ),
          lang.contains('ja') ? ListTile(
            title: Text('japanese'.tr(), style: TextStyle(color: textColor, fontSize: 14)),
            trailing: Icon(context.locale.toString()=='ja'?Icons.radio_button_checked:Icons.radio_button_off, color: primaryColor, size: 18),
            onTap: context.locale.toString() != 'ja' ? () async {
              accFunc.switchLang(context, 'ja', user);
            } : null,
          ) : Container(),
          lang.contains('zh') ? ListTile(
            title: Text('chinese'.tr(), style: TextStyle(color: textColor, fontSize: 14)),
            trailing: Icon(context.locale.toString()=='zh'?Icons.radio_button_checked:Icons.radio_button_off, color: primaryColor, size: 18),
            onTap: context.locale.toString() != 'zh' ? () async {
              accFunc.switchLang(context, 'zh', user);
            } : null,
          ) : Container(),
          lang.contains('ko') ? ListTile(
            title: Text('korean'.tr(), style: TextStyle(color: textColor, fontSize: 14)),
            trailing: Icon(context.locale.toString()=='ko'?Icons.radio_button_checked:Icons.radio_button_off, color: primaryColor, size: 18),
            onTap: context.locale.toString() != 'ko' ? () async {
              accFunc.switchLang(context, 'ko', user);
            } : null,
          ) : Container(),
          lang.contains('ar') ? ListTile(
            title: Text('العربية', style: TextStyle(color: textColor, fontSize: 14)),
            trailing: Icon(context.locale.toString()=='ar'?Icons.radio_button_checked:Icons.radio_button_off, color: primaryColor, size: 18),
            onTap: context.locale.toString() != 'ar' ? () async {
              accFunc.switchLang(context, 'ar', user);
            } : null,
          ) : Container()
        ],
      ),
    );
  }
}