import 'package:app_settings/app_settings.dart';
import 'package:auto_route/auto_route.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/foundation.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/components/template.dart';
import 'package:telnow_mobile_new/src/layouts/web/password.dart';
import 'package:telnow_mobile_new/src/utils/U.dart';
import 'package:telnow_mobile_new/src/utils/extensions.dart';
import 'package:telnow_mobile_new/src/utils/provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:telnow_mobile_new/src/utils/ui_service.dart';

import '../../utils/C.dart';

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

  @override
  State<WebAccountPage> createState() => _WebAccountPageState();
}

class _WebAccountPageState extends State<WebAccountPage> {
  final AccountFunction accFunc = AccountFunction();

  bool isDeniedNotifPermission = false;
  bool serDis = false;
  bool dnd = false;
  bool autoTranslate = false;
  List lang = [];
  var codeOflang = {};
  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();
    lang = license['_validLang'] ?? [];
    setState(() {
      serDis = U.servantDisplay();
      autoTranslate = U.autoTranslate();
    });
  }

  @override
  Widget build(BuildContext context) {
    final UserModule userModule = Provider.of<UserModule>(context);
    dnd = userModule.dndStatus();

    codeOflang = {
      "id": 'bahasa'.tr(),
      "en": 'english'.tr(),
      "ja": 'japanese'.tr(),
      "zh": 'chinese'.tr(),
      "ko": 'korean'.tr(),
      "ar": 'arabic'.tr(),
      "de": 'german'.tr(),
      "fr": 'french'.tr(),
      "hi": 'hindi'.tr(),
      "nl": 'dutch'.tr()
    };
    return userModule.user().isNotEmpty ? Scaffold(
      backgroundColor: backgroundColor,
      appBar: PreferredSize(preferredSize: Size.fromHeight(0), child: AppBar(elevation: 0, backgroundColor: primaryColor)),
      body: Column(
        children: [
          Container(
            padding: EdgeInsets.symmetric(vertical: 25, horizontal: 100),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text('account'.tr(), style: TextStyle(color: textColor, fontSize: 17, fontWeight: FontWeight.w500), overflow: TextOverflow.ellipsis),
                GestureDetector(
                  child: Text('buttonBack'.tr(), style: TextStyle(color: primaryColor, fontSize: 14)),
                  onTap: (){
                    var pid = U.getPidFromUrl(context.router.currentUrl);
                    context.router.removeLast();
                    context.navigateToPath("/app/$pid/menu");
                  },
                ).withHover()
              ],
            ),
          ),
          divider(),
          Expanded(
            child: SingleChildScrollView(
              padding: EdgeInsets.symmetric(vertical: 25, horizontal: 100),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Expanded(
                    child: Column(
                      children: [
                        Container(
                          padding: EdgeInsets.all(20),
                          decoration: BoxDecoration(color: Colors.white, border: Border.all(color: textColor.withValues(alpha: 0.15)), borderRadius: BorderRadius.all(Radius.circular(12))),
                          child: Column(
                            children: [
                              Container(
                                padding: EdgeInsets.only(bottom: 20),
                                child: Row(
                                  children: [
                                    CircleAvatar(
                                      backgroundColor: primaryColor,
                                      radius: 25,
                                      child: Text(userModule.user()['name'][0].toString().toUpperCase(), style: TextStyle(color: Colors.white)),
                                    ),
                                    SizedBox(width: 16),
                                    Expanded(child: Text(userModule.user()['name'], style: TextStyle(fontSize: 16, fontWeight: FontWeight.w500, color: textColor), maxLines: 2, overflow: TextOverflow.ellipsis))
                                  ],
                                ),
                              ),
                              separator(),
                              Container(
                                padding: EdgeInsets.only(top: 20),
                                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(), userModule.user()['relatedTo'] ?? userModule.user()['userId'], size: 16, opacity: 0.75),
                                    SizedBox(height: 12),
                                    textHorizontal('location'.tr(), userModule.user()['location'] ?? '-', size: 16, opacity: 0.75),
                                    SizedBox(height: 12),
                                    textHorizontal('servantGroup'.tr(), userModule.user()['requestTypeListDescriptionMobile'] != null ? userModule.user()['requestTypeListDescriptionMobile'].toLowerCase() == 'semua' ? 'all'.tr() : userModule.user()['requestTypeListDescriptionMobile'] : '-', size: 16, opacity: 0.75),
                                  ],
                                ),
                              ),
                            ],
                          ),
                        ),
                        Padding(
                          padding: const EdgeInsets.only(top: 30),
                          child: Center(child: Column(
                            children: [
                              Text("${"version".tr()} ${ApiAuthProvider().displayVersion}"),
                              Text("Build ${ApiAuthProvider().buildNumber}", style: TextStyle(fontSize: 13),),
                            ],
                          )),
                        )
                      ],
                    ),
                  ),
                  SizedBox(width: 50),
                  Expanded(
                    child: Container(
                      padding: EdgeInsets.all(20),
                      decoration: BoxDecoration(color: Colors.white, border: Border.all(color: textColor.withValues(alpha: 0.15)), borderRadius: BorderRadius.all(Radius.circular(12))),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          if (userModule.houseKeeping()) 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(
                                    onTap: (){
                                      if(userModule.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(userModule.user()['id'], dnd);
                                            if(res){
                                              userModule.setDndStatus(!dnd);
                                            }
                                        });
                                      }
                                    },
                                    child: Container(
                                      decoration: BoxDecoration(border: Border.all(color: userModule.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: userModule.user()['checkedIn']?primaryColor:Colors.black38, borderRadius: BorderRadius.all(Radius.circular(20))),
                                          ):SizedBox(width: 20, height: 20),
                                          dnd?Container(
                                            width: 20, height: 20, decoration: BoxDecoration(color: userModule.user()['checkedIn']?primaryColor:Colors.black38, borderRadius: BorderRadius.all(Radius.circular(20))),
                                          ):SizedBox(width: 20, height: 20),
                                        ],
                                      ),
                                    ),
                                  ).withHover(),
                                ],
                              )
                            ],
                          ),
                          if(userModule.houseKeeping()) Padding(padding: EdgeInsets.symmetric(vertical: 16), child: separator()),
                          if(!userModule.user()['_profile']['isRoom']) 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))),
                                          ):SizedBox(width: 20, height: 20),
                                          serDis?Container(
                                            width: 20, height: 20, decoration: BoxDecoration(color: primaryColor, borderRadius: BorderRadius.all(Radius.circular(20))),
                                          ):SizedBox(width: 20, height: 20),
                                        ],
                                      ),
                                    ),
                                    onTap: (){
                                      setState(() {
                                        if(serDis){
                                          U.setServantDisplay(false);
                                          serDis = false;
                                        }
                                        else{
                                          U.setServantDisplay(true);
                                          serDis = true;
                                        }
                                      });
                                    },
                                  ).withHover(),
                                ],
                              )
                            ],
                          ),
                          if(!userModule.user()['_profile']['isRoom']) Padding(padding: EdgeInsets.symmetric(vertical: 16), child: separator()),
                          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()),
                              ).withHover(),
                              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))),
                                            ):SizedBox(width: 20, height: 20),
                                            autoTranslate?Container(
                                              width: 20, height: 20, decoration: BoxDecoration(color: primaryColor, borderRadius: BorderRadius.all(Radius.circular(20))),
                                            ):SizedBox(width: 20, height: 20),
                                          ],
                                        ),
                                      ),
                                      onTap: (){
                                        setState(() {
                                          if(autoTranslate){
                                            U.setAutoTranslate(false);
                                            autoTranslate = false;
                                          }
                                          else{
                                            U.setAutoTranslate(true);
                                            autoTranslate = true;
                                          }
                                        });
                                      },
                                    ).withHover(),
                                  ],
                                ),
                              ),
                              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: WebPasswordPage(user: Provider.of<UserModule>(context, listen: false).user()))).then((value) {
                                  value??false;
                                  if (value) UIService.showSuccess('messagePassChanged'.tr());
                                }),
                              ).withHover(),
                              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())),
                                        ],
                                      );
                                    },
                                  );
                                },
                              ).withHover(),
                            ],
                          ),
                          separator(),
                          GestureDetector(
                            child: Container(
                              color: Colors.white,
                              padding: EdgeInsets.only(top: 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.height/2;
                              var pid = U.getPidFromUrl(context.router.currentUrl);
                              var qrData = '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: qrData,
                                            version: QrVersions.auto,
                                            gapless: true,
                                          ),
                                        ),
                                        SizedBox(height: 15),
                                        Text("show_qr_desc".tr(), style: TextStyle(fontSize: 14, color: Colors.black), textAlign: TextAlign.center)
                                      ],
                                    ),
                                  );
                                },
                              );
                            },
                          ).withHover(),
                          if(isDeniedNotifPermission && !kIsWeb) ...[
                            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);
                              }),
                            ).withHover(),
                            Padding(padding: EdgeInsets.symmetric(vertical: 16), child: separator()),
                          ]
                        ],
                      ),
                    ),
                  )
                ],
              )
            ),
          )
        ],
      ),
    ) : userModule.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) {
    showDialog(
        context: context,
        builder: (BuildContext contextDialog) {
          return AlertDialog(
            contentPadding: EdgeInsets.symmetric(vertical: 0, horizontal: 10),
            content: 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, contextDialog),
                SizedBox(height: 16)
              ],
            ),
          );
        }
    );
  }

  listOfLang(user, cd){
    if(mounted) {
      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('id', user);
                Navigator.of(cd).pop();
              } : 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('en', user);
                Navigator.of(cd).pop();
              } : null,
            ),
            if(lang.length - 1 > 1) ListTile(
              title: Text(codeOflang[lang[2]], style: TextStyle(color: textColor, fontSize: 14)),
              trailing: Icon(context.locale.toString()==lang[2]?Icons.radio_button_checked:Icons.radio_button_off, color: primaryColor, size: 18),
              onTap: context.locale.toString() != lang[2] ? () async {
                accFunc.switchLang(1, user);
                Navigator.of(cd).pop();
              } : null,
            ),
            if(lang.length - 1 > 2) ListTile(
              title: Text(codeOflang[lang[3]], style: TextStyle(color: textColor, fontSize: 14)),
              trailing: Icon(context.locale.toString()==lang[3]?Icons.radio_button_checked:Icons.radio_button_off, color: primaryColor, size: 18),
              onTap: context.locale.toString() != lang[3] ? () async {
                accFunc.switchLang(2, user);
                Navigator.of(cd).pop();
              } : null,
            ),
            if(lang.length - 1 > 3) ListTile(
              title: Text(codeOflang[lang[4]], style: TextStyle(color: textColor, fontSize: 14)),
              trailing: Icon(context.locale.toString()==lang[4]?Icons.radio_button_checked:Icons.radio_button_off, color: primaryColor, size: 18),
              onTap: context.locale.toString() != lang[4] ? () async {
                accFunc.switchLang(3, user);
                Navigator.of(cd).pop();
              } : null,
            ),
          ],
        ),
      );
    } else {
      return SizedBox.shrink();
    }
  }
}
