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/extensions/string_extensions.dart';
import 'package:tangheem/extensions/widget_extensions.dart';
import 'package:tangheem/models/authentication_user_model.dart';
import 'package:tangheem/models/content_info_model.dart';
import 'package:tangheem/models/navigation_model.dart';
import 'package:tangheem/models/quick_links_model.dart';
import 'package:tangheem/new_ui/screens/about_screen.dart';
import 'package:tangheem/ui/dialogs/app_menu_dialog.dart';
import 'package:tangheem/ui/dialogs/change_password_dialog.dart';
import 'package:tangheem/ui/dialogs/general_dialog.dart';
import 'package:tangheem/ui/screens/bookmark_screen.dart';
import 'package:tangheem/ui/screens/content_info_screen.dart';
import 'package:tangheem/new_ui/screens/home_screen.dart';
import 'package:tangheem/ui/screens/login_screen.dart';
import 'package:tangheem/ui/screens/member_screen.dart';
import 'package:tangheem/ui/screens/pdf_viewer_screen.dart';
import 'package:tangheem/ui/screens/quran_screen.dart';
import 'package:tangheem/widgets/video_player_widget.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:youtube_player_flutter/youtube_player_flutter.dart';

class CommonHomeParent extends StatefulWidget {
  CommonHomeParent({Key key}) : super(key: key);

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

class _CommonHomeParentState extends State<CommonHomeParent> {
  int index = 0;
  SharedPreferences prefs;

  List<Widget> screens = [
    HomeScreen(),
    AboutScreen(),
    QuranScreen(),
    ContentInfoScreen(contentId: 2),
    MemberScreen(),
    PdfListScreen(),
  ];

  @override
  void initState() {
    super.initState();
    checkScreenMode();
    getPrefs();
  }

  int fontSize;

  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();
  }

  void checkScreenMode() {
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      if (MediaQuery.of(context).orientation == Orientation.portrait) {
        await showDialog(
          context: context,
          barrierColor: Colors.white.withOpacity(0.2),
          builder: (BuildContext context) => GeneralDialog(),
        );
      }
      getWelcomeVideo();
      // showWelcomeVideoDialog();
    });
  }

  void getWelcomeVideo() async {
    Utils.showLoading(context);
    try {
      String link = await TangheemUserApiClient().getWelcomeVideo();
      Utils.hideLoading(context);
      link = YoutubePlayer.convertUrlToId(link);
      showWelcomeVideoDialog(link);
    } catch (ex) {
      if (mounted) Utils.handleException(ex, null);
      Utils.hideLoading(context);
    }
  }

  void showWelcomeVideoDialog(String permLink) async {
    prefs = await SharedPreferences.getInstance();
    String link = prefs.getString(GlobalConsts.welcomeVideoUrl) ?? permLink;
    if (permLink == link) {
      await prefs.setString(GlobalConsts.welcomeVideoUrl, permLink);
      bool showDialog = prefs.getBool(GlobalConsts.doNotShowWelcomeVideo) ?? false;
      if (showDialog) {
        return;
      }
    } else {
      await prefs.setString(GlobalConsts.welcomeVideoUrl, permLink);
    }
    await prefs.setBool(GlobalConsts.doNotShowWelcomeVideo, false);
    showDialog(
      context: context,
      barrierColor: Colors.white.withOpacity(0.2),
      builder: (BuildContext context) => VideoPlayerWidget(permLink),
    );
  }

  @override
  Widget build(BuildContext context) {
    bool isPortrait = MediaQuery.of(context).orientation == Orientation.portrait;
    return Scaffold(
      backgroundColor: Color(0xffF4F4F4),
      resizeToAvoidBottomInset: true,
      body: SafeArea(
        bottom: true,
        left: false,
        top: false,
        right: false,
        child: Stack(
          children: [
            screens[index],
            if (MediaQuery.of(context).viewInsets.bottom == 0)
              Align(
                alignment: isPortrait ? Alignment.bottomCenter : Alignment.centerRight,
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    isPortrait
                        ? Container(
                            height: 58,
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(29.0),
                              color: Colors.white,
                              border: Border.all(color: ColorConsts.borderColor, width: 1),
                            ),
                            padding: EdgeInsets.only(left: 30, right: 30),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [for (int i = 0; i < icons.length; i++) getBottomNavigationItem(i, 0, isPortrait)],
                            ),
                          )
                        : Container(
                            width: 58,
                            margin: EdgeInsets.only(top: 50, right: 24),
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(29.0),
                              color: Colors.white,
                              border: Border.all(color: ColorConsts.borderColor, width: 1),
                            ),
                            padding: EdgeInsets.only(top: 30, bottom: 30),
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [for (int i = 0; i < icons.length; i++) getBottomNavigationItem(i, 0, isPortrait)],
                            ),
                          ).expanded,
                    (isPortrait
                            ? Container(
                                height: 26,
                                margin: EdgeInsets.only(top: 16),
                                padding: EdgeInsets.only(right: 16, left: 12),
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(29.0),
                                  color: ColorConsts.brownLightColor,
                                ),
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                  children: [
                                    Icon(Icons.play_arrow_outlined, size: 20, color: Colors.white),
                                    "تصفح وتحميل الموسوعة".toText(13),
                                  ],
                                ))
                            : Container(
                                width: 58,
                                margin: EdgeInsets.only(top: 6, right: 30),
                                padding: isPortrait ? EdgeInsets.only(right: 16, left: 12) : EdgeInsets.only(top: 4, bottom: 4),
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(29.0),
                                  color: ColorConsts.brownLightColor,
                                ),
                                alignment: Alignment.center,
                                child: Icon(Icons.play_arrow_outlined, size: 20, color: Colors.white),
                              ))
                        .onPress(() {
                      if (index != 5)
                        setState(() {
                          index = 5;
                        });
                    }),
                  ],
                ).paddingOnly(left: 16, right: 16, bottom: 16),
              ),
          ],
        ),
      ),
    );
  }

  List<String> icons = [
    "assets/icons/new/home.svg",
    "assets/icons/new/intro.svg",
    "assets/icons/new/quran.svg",
    "assets/icons/new/search.svg",
    "assets/icons/new/members.svg",
  ];
  List<double> sizes = [26, 26, 36, 26, 26];

  Widget getBottomNavigationItem(int _index, int minusValue, bool isPortrait) {
    List<Widget> list = [
      SvgPicture.asset(
        icons[_index],
        width: sizes[_index] - minusValue,
        height: sizes[_index] - minusValue,
        color: index == _index ? ColorConsts.brownColor : ColorConsts.darkText,
      ).expanded,
      if (index == _index)
        Container(
          height: isPortrait ? 3 : sizes[_index] - minusValue,
          color: ColorConsts.brownColor,
          width: isPortrait ? sizes[_index] - minusValue : 3,
        ),
    ];

    Widget child = isPortrait
        ? Column(
            mainAxisSize: MainAxisSize.min,
            children: list,
          )
        : Row(
            mainAxisSize: MainAxisSize.min,
            children: list,
          );

    return child.onPress(() {
      if (_index == 3) {
        showMenu();
        return;
      }
      if (index != _index)
        setState(() {
          index = _index;
        });
    });
  }

  void showMenu() {
    showDialog(
      context: context,
      barrierColor: Colors.white.withOpacity(0.2),
      builder: (BuildContext context) => AppMenuDialog(
        onFontDecrease: () {
          if (fontSize <= 12) {
            Utils.showToast("وصل حجم الخط إلى الحد الأدنى للحجم");
            return;
          }
          fontSize -= 2;
          prefs.setInt(GlobalConsts.fontZoomSize, fontSize);
          Utils.showToast("تم تقليل حجم الخط");
        },
        onFontIncrease: () {
          if (fontSize >= 36) {
            Utils.showToast("وصل حجم الخط إلى الحد الأقصى للحجم");
            return;
          }
          fontSize += 2;
          prefs.setInt(GlobalConsts.fontZoomSize, fontSize);
          Utils.showToast("زيادة حجم الخط");
        },
        goToIndex: (_index) {
          Navigator.pop(context);
          if (index != _index)
            setState(() {
              index = _index;
            });
        },
      ),
    );
  }
}
