import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:tangheem/api/tangheem_user_api_client.dart';
import 'package:tangheem/api/user_api_client.dart';
import 'package:tangheem/app_state/app_state.dart';
import 'package:tangheem/classes/colors.dart';
import 'package:tangheem/classes/consts.dart';
import 'package:tangheem/classes/utils.dart';
import 'package:tangheem/models/authentication_user_model.dart';
import 'package:tangheem/models/navigation_model.dart';
import 'package:tangheem/models/quick_links_model.dart';
import 'package:tangheem/ui/dialogs/change_password_dialog.dart';
import 'package:tangheem/ui/screens/bookmark_screen.dart';
import 'package:tangheem/ui/screens/content_info_screen.dart';
import 'package:tangheem/ui/screens/home_screen.dart';
import 'package:tangheem/ui/screens/login_screen.dart';
import 'package:tangheem/ui/screens/pdf_viewer_screen.dart';
import 'package:url_launcher/url_launcher.dart';

class CommonAppbar extends StatefulWidget {
  final bool showDrawer;
  final Widget child;
  final bool isFirst;

  CommonAppbar({Key key, this.showDrawer = false, @required this.child, this.isFirst = false}) : super(key: key);

  @override
  _CommonAppbarState createState() {
    return _CommonAppbarState();
  }
}

class _CommonAppbarState extends State<CommonAppbar> {
  final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
  List<QuickLinksData> quickLinks = [];
  List<NavigationDataModel> navigationList = [];

  @override
  void initState() {
    super.initState();
    getPrefs();
    getNavigation();
    getQuickLinks();
    //getCopyRight();
  }

  // void getCopyRight() async {
  //   if (AppState().getContentInfoModel == null) {
  //     try {
  //       var model = await TangheemUserApiClient().getContentInfo(3);
  //       var contentList = model?.data ?? [];
  //       if (contentList.length > 0) {
  //         _copyRight = contentList.first;
  //         AppState().setContentInfoModel(_copyRight);
  //       }
  //     } catch (ex) {}
  //   } else {
  //     _copyRight = AppState().getContentInfoModel;
  //   }
  //   setState(() {});
  // }

  void getNavigation() async {
    if (AppState().getNavigationModel?.data == null) {
      try {
        var model = await TangheemUserApiClient().getNavigation();
        navigationList = model?.data ?? [];
        navigationList.sort((a, b) => a.orderNo.compareTo(b.orderNo));
        AppState().setNavigationModel(model);
      } catch (ex) {}
    } else {
      navigationList = AppState().getNavigationModel.data;
    }
    setState(() {});
  }

  void getQuickLinks() async {
    if (widget.showDrawer) {
      try {
        quickLinks = (await TangheemUserApiClient().quickLinks())?.data ?? [];
        quickLinks = quickLinks.where((element) => element.position == "down").toList();
        quickLinks.sort((a, b) => a.orderNo.compareTo(b.orderNo));
      } catch (ex) {}
      setState(() {});
    }
  }

  int fontSize;
  SharedPreferences prefs;

  void getPrefs() async {
    prefs = await SharedPreferences.getInstance();
    fontSize = prefs.getInt(GlobalConsts.fontZoomSize) ?? 18;
    String userAuth = prefs.getString(GlobalConsts.userAuthData);
    if (userAuth != null) {
      AuthenticationUserModel authenticationUserModel = AuthenticationUserModel.fromJson(jsonDecode(userAuth));
      AppState().setAuthenticationModel(authenticationUserModel);
    }
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: widget.showDrawer ? _scaffoldKey : null,
      drawer: widget.showDrawer ? drawerView() : null,
      resizeToAvoidBottomInset: true,
      drawerScrimColor: Colors.black.withOpacity(.3),
      body: SafeArea(
        child: Column(
          children: [
            Container(
              color: Colors.white,
              height: 100,
              padding: EdgeInsets.only(top: 8, bottom: 8, right: 16),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  if (!widget.isFirst)
                    IconButton(
                      icon: Icon(widget.showDrawer ? Icons.menu : Icons.arrow_back_ios, color: ColorConsts.textGrey),
                      padding: EdgeInsets.only(left: 16),
                      onPressed: () {
                        if (widget.showDrawer) {
                          _scaffoldKey.currentState.openDrawer();
                        } else {
                          Navigator.pop(context);
                        }
                      },
                    ),
                  if (!widget.showDrawer)
                    IconButton(
                      icon: Icon(widget.showDrawer ? Icons.home : Icons.home, color: ColorConsts.textGrey),
                      padding: EdgeInsets.only(left: 16),
                      onPressed: () {
                        Navigator.popUntil(context, ModalRoute.withName(HomeScreen.routeName));
                      },
                    ),
                  Expanded(child: SizedBox()),
                  Hero(
                    tag: "logo",
                    child: SvgPicture.asset(
                      "assets/logos/tangheem_logo.svg",
                      height: 100,
                      width: 100,
                      alignment: Alignment.centerRight,
                    ),
                  )
                ],
              ),
            ),
            Expanded(
              child: Directionality(textDirection: TextDirection.rtl, child: widget.child),
            ),
          ],
        ),
      ),
    );
  }

  void updatePassword(String email, String oldPassword, String password) async {
    Utils.showLoading(context);
    try {
      await UserApiClient().updatePassword(email, oldPassword, password);
    } catch (ex) {
      if (mounted) Utils.handleException(ex, null);
      Utils.hideLoading(context);
      return;
    } finally {
      Utils.hideLoading(context);
    }
    Navigator.pop(context);
    Utils.showToast("تم تغيير كلمة المرور بنجاح");
  }

  Widget drawerView() {
    var height = MediaQuery.of(context).padding.top;
    return Drawer(
      elevation: 0,
      child: Container(
        color: Colors.white,
        child: SafeArea(
          bottom: true,
          top: false,
          right: false,
          left: false,
          maintainBottomViewPadding: true,
          child: Builder(
            builder: (context) {
              bool isPortrait = MediaQuery.of(context).orientation == Orientation.portrait;
              Widget listContents = ListView.builder(
                  shrinkWrap: true,
                  physics: BouncingScrollPhysics(),
                  padding: EdgeInsets.only(left: 24, right: 24),
                  itemCount: navigationList.length,
                  itemBuilder: (context, index) {
                    String icon = "assets/icons/${navigationList[index].mobileFontIcon}.svg";
                    var subList = navigationList.where((element) => element.parentId == navigationList[index].navigationId).toList();
                    return Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        if (navigationList[index].parentId == 1)
                          myListItem(icon, navigationList[index].navigationText, navigationList[index].orderNo == 1 ? true : false, onTap: () {
                            String url = navigationList[index]?.mobileNavigationUrl ?? "";
                            if (url.isEmpty || url.length < 2) {
                              return;
                            }
                            Navigator.pushNamed(context, url, arguments: null);
                          }),
                        for (var subItem in subList)
                          Container(
                            width: double.infinity,
                            child: Row(
                              children: [
                                Expanded(
                                  child: myListItem("assets/icons/${subItem.mobileFontIcon}.svg", subItem.navigationText, false, onTap: () {
                                    String url = subItem.mobileNavigationUrl ?? "";
                                    if (url.isEmpty) {
                                      return;
                                    }
                                    var contentId;
                                    if (subItem.mobileNavigationUrl == "/introduction") {
                                      url = ContentInfoScreen.routeName;
                                      contentId = 2;
                                    } else if (subItem.mobileNavigationUrl == "/encyclopedia") {
                                      url = ContentInfoScreen.routeName;
                                      contentId = 1;
                                    } else if (subItem.mobileNavigationUrl == "/tangheempdf") {
                                      url = PdfListScreen.routeName;
                                      contentId = 8;
                                    }
                                    Navigator.pushNamed(context, url, arguments: contentId);
                                  }),
                                ),
                                Container(
                                  height: 40,
                                  margin: EdgeInsets.only(right: 17, left: 10),
                                  child: VerticalDivider(color: ColorConsts.primaryBlack, thickness: .7, width: 1),
                                ),
                              ],
                            ),
                          )
                      ],
                    );
                  });
              if (isPortrait) {
                listContents = Expanded(child: listContents);
              }
              List<Widget> list = [
                Container(
                  height: 100 + height,
                  padding: EdgeInsets.only(left: 0, top: height),
                  alignment: Alignment.centerLeft,
                  child: IconButton(
                    icon: Icon(Icons.clear, color: ColorConsts.textGrey),
                    onPressed: () {
                      if (_scaffoldKey.currentState.isDrawerOpen) {
                        Navigator.pop(context);
                      }
                    },
                  ),
                ),
                Container(
                  margin: EdgeInsets.only(top: 8, bottom: 16),
                  padding: EdgeInsets.only(left: 16, right: 16),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: [
                      commonIconButton("assets/icons/bookmark.svg", () {
                        Navigator.pushNamed(context, BookmarkScreen.routeName);
                      }),
                      commonIconButton("assets/icons/increase_size.svg", () {
                        if (fontSize >= 36) {
                          Utils.showToast("وصل حجم الخط إلى الحد الأقصى للحجم");
                          return;
                        }
                        fontSize += 2;
                        prefs.setInt(GlobalConsts.fontZoomSize, fontSize);
                        Utils.showToast("زيادة حجم الخط");
                      }),
                      commonIconButton("assets/icons/reduce_size.svg", () {
                        if (fontSize <= 12) {
                          Utils.showToast("وصل حجم الخط إلى الحد الأدنى للحجم");
                          return;
                        }
                        fontSize -= 2;
                        prefs.setInt(GlobalConsts.fontZoomSize, fontSize);
                        Utils.showToast("تم تقليل حجم الخط");
                      }),
                      commonIconButton("assets/icons/user_logged.svg", () {
                        if (AppState().isUserLogin) {
                          Utils.showToast("أنت بالفعل تسجيل الدخول");
                          return;
                        }
                        Navigator.pushNamed(context, LoginScreen.routeName);
                      }),
                      if (AppState().isUserLogin)
                        Expanded(
                          child: PopupMenuButton(
                              padding: EdgeInsets.fromLTRB(0, 0, 0, 0),
                              onSelected: (int index) async {
                                if (index == 0) {
                                  Navigator.pop(context);
                                  Future.delayed(Duration(milliseconds: 200), () {
                                    showDialog(
                                      context: context,
                                      barrierColor: ColorConsts.secondaryWhite.withOpacity(0.8),
                                      builder: (BuildContext context) => ChangePasswordDialog(
                                        onPassword: (oldPassword, password) => updatePassword(AppState().userEmail, oldPassword, password),
                                      ),
                                    );
                                  });
                                } else {
                                  SharedPreferences prefs = await SharedPreferences.getInstance();
                                  await prefs.remove(GlobalConsts.userAuthData);
                                  AppState().setAuthenticationModel(null);
                                  Utils.showToast("تسجيل خروج المستخدم");
                                  Navigator.pop(context);
                                }
                              },
                              icon: SvgPicture.asset("assets/icons/fa_key.svg", height: 25, width: 30, color: ColorConsts.textGrey1),
                              itemBuilder: (_) => <PopupMenuItem<int>>[
                                    PopupMenuItem(
                                      value: 0,
                                      padding: EdgeInsets.fromLTRB(0, 0, 0, 0),
                                      height: 24,
                                      child: Center(
                                        child: Text(
                                          'تغيير كلمة المرور',
                                          style: TextStyle(color: ColorConsts.primaryBlack, fontSize: 14),
                                        ),
                                      ),
                                    ),
                                    PopupMenuItem(
                                      value: 1,
                                      padding: EdgeInsets.fromLTRB(0, 0, 0, 0),
                                      height: 24,
                                      child: Center(
                                        child: Text(
                                          'تسجيل خروج',
                                          style: TextStyle(color: ColorConsts.primaryBlack, fontSize: 14),
                                        ),
                                      ),
                                    ),
                                  ]),
                        ),
                    ],
                  ),
                ),
                listContents,
                Container(
                  margin: EdgeInsets.only(top: 16, bottom: 12),
                  padding: EdgeInsets.only(left: 32, right: 32),
                  child: Row(
                    children: [
                      for (QuickLinksData _quickLink in quickLinks)
                        commonIconButton(ApiConsts.baseUrl + _quickLink.exposeFilePath, () {
                          //for live production server
                          //     commonIconButton( _quickLink.exposeFilePath, () {
                          _launchURL(_quickLink.imageUrl);
                        }, size: 35, isAsset: false),
                    ],
                  ),
                ),
                Padding(
                  padding: EdgeInsets.only(left: 32, right: 32, bottom: 8),
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text(
                        "Powered by Cloud Solutions",
                        maxLines: 1,
                        textAlign: TextAlign.right,
                        style: TextStyle(fontSize: 14, color: Colors.black87),
                      ),
                      SizedBox(width: 8),
                      SvgPicture.asset("assets/logos/cloud_logo.svg", width: 30, height: 30)
                    ],
                  ),
                )
              ];
              return isPortrait ? Column(children: list) : ListView(children: list);
            },
          ),
        ),
      ),
    );
  }

  void _launchURL(String _url) async => await canLaunch(_url) ? await launch(_url) : throw 'Could not launch $_url';

  Widget commonIconButton(String icon, VoidCallback onPressed, {double size, bool isAsset = true}) {
    return Expanded(
      child: IconButton(
          padding: EdgeInsets.zero,
          icon: isAsset ? SvgPicture.asset(icon, height: size ?? 25, width: size ?? 30) : Image.network(icon, height: size ?? 25, width: size ?? 30),
          onPressed: () {
            Navigator.pop(context);
            Future.delayed(Duration(milliseconds: 200), () => onPressed());
          }),
    );
  }

  Widget myListItem(String icon, String title, bool isSelected, {VoidCallback onTap}) {
    return InkWell(
      onTap: () {
        Navigator.pop(context);
        if (onTap != null) {
          Future.delayed(Duration(milliseconds: 200), () => onTap());
        }
      },
      child: Container(
        height: 40,
        padding: EdgeInsets.only(left: 8, right: 8),
        alignment: Alignment.centerRight,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(6),
          gradient: isSelected
              ? LinearGradient(
                  stops: [0.0, 0.5],
                  begin: Alignment.topCenter,
                  end: Alignment.bottomCenter,
                  colors: [ColorConsts.gradientPink, ColorConsts.gradientOrange],
                )
              : null,
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(
              title,
              style: TextStyle(fontSize: 14, color: isSelected ? Colors.white : ColorConsts.textGrey),
            ),
            SizedBox(width: 8),
            SvgPicture.asset(icon, height: 20, width: 20, color: isSelected ? Colors.white : ColorConsts.textGrey),
          ],
        ),
      ),
    );
  }
}
