import 'package:firebase_analytics/firebase_analytics.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/painting.dart';
import 'package:flutter/services.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/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/int_extensions.dart';
import 'package:tangheem/extensions/string_extensions.dart';
import 'package:tangheem/extensions/widget_extensions.dart';
import 'package:tangheem/models/aya_tangheem_type.dart';
import 'package:tangheem/models/content_info_model.dart';
import 'package:tangheem/models/quick_links_model.dart';
import 'package:tangheem/models/surah_model.dart';
import 'package:tangheem/models/tangheem_type_model.dart';
import 'package:tangheem/ui/dialogs/general_dialog.dart';
import 'package:tangheem/ui/screens/tangheem_screen.dart';
import 'package:tangheem/widgets/common_dropdown_button.dart';
import 'package:tangheem/widgets/video_player_widget.dart';
import 'package:url_launcher/url_launcher.dart';

class HomeScreen extends StatefulWidget {
  static const String routeName = "/";

  HomeScreen({Key key}) : super(key: key);

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

class _HomeScreenState extends State<HomeScreen> {
  TextEditingController _searchController = TextEditingController();
  FocusNode _searchFocusNode = FocusNode();

  ValueNotifier<List<String>> _tangheemListNotifier = ValueNotifier([]);

  List<String> _surahList = [];
  int _selectedSurah = -1;
  int _selectedTangheemType = -1;

  SurahModel _surahModel;
  TangheemType _tangheemType;
  String _tangheemDiscription;
  List<QuickLinksData> quickLinks;

  @override
  void initState() {
    super.initState();
    SystemChannels.textInput.invokeMethod('TextInput.hide');
    getSurahAndTangheemTypes();
  }

  void getSurahAndTangheemTypes() async {
    Utils.showLoading(context);
    try {
      if (AppState().tangheemDiscription == null) {
        ContentInfoModel _contentInfoModel = await TangheemUserApiClient().getContentInfo(4);
        _tangheemDiscription = _contentInfoModel.data.first.content;
        AppState().tangheemDiscription = _tangheemDiscription;
      } else {
        _tangheemDiscription = AppState().tangheemDiscription;
      }

      if (AppState().quickLinks == null) {
        quickLinks = (await TangheemUserApiClient().quickLinks())?.data ?? [];
        quickLinks = quickLinks.where((element) => element.position == "down").toList();
        quickLinks.sort((a, b) => a.orderNo.compareTo(b.orderNo));
        AppState().quickLinks = quickLinks;
      } else {
        quickLinks = AppState().quickLinks;
      }

      if (AppState().getSurahModel == null) {
        _surahModel = await TangheemUserApiClient().getSurahs();
        AppState().setSurahModel(_surahModel);
      } else {
        _surahModel = AppState().getSurahModel;
      }

      _surahList = _surahModel.data.map((element) => element.nameAR).toList();
      await getTangheemTypes();
      TangheemUserApiClient().addStatistics(1);
      // AppState().setAnalytics(widget.analytics);
      // await widget.analytics.setAnalyticsCollectionEnabled(true);
      // await widget.analytics.setCurrentScreen(screenName: "home");
      setState(() {});
      Utils.hideLoading(context);
    } catch (ex) {
      Utils.hideLoading(context);
      if (mounted) Utils.handleException(ex, null);
    }
    // checkScreenMode();
  }

  void filterTangheemTypesListBySurah(int surahNo, {bool showLoading = true}) async {
    if (showLoading) Utils.showLoading(context);
    try {
      AyaTangheemType ayaTangheemType = await TangheemUserApiClient().getAyaTangheemType(surahNo, null);

      var tangheemType = _tangheemType?.data?.where((element) => element.isActive)?.toList() ?? [];
      var ayaTangheem = ayaTangheemType?.data?.where((element) => element.isActive)?.toList() ?? [];
      var result = tangheemType.where((tangheem) => ayaTangheem.any((element) => tangheem.tangheemTypeId == element.tangheemTypeId)).toList() ?? [];
      _tangheemListNotifier.value = result?.map((element) => element.tangheemTypeName)?.toList() ?? [];
      if (showLoading) Utils.hideLoading(context);
    } catch (ex) {
      if (showLoading) Utils.hideLoading(context);
      if (mounted) Utils.handleException(ex, null);
    }
  }

  void filterSurahListByTangheemType(String tangheemName) async {
    Utils.showLoading(context);
    try {
      AyaTangheemType ayaTangheemType = await TangheemUserApiClient().getAyaTangheemType(null, tangheemName);
      _surahList = _surahModel.data.where((surah) => ayaTangheemType.data.any((element) => surah.id == element.surahNo)).toList().map((element) => element.nameAR).toList();
      setState(() {});
      Utils.hideLoading(context);
    } catch (ex) {
      Utils.hideLoading(context);
      if (mounted) Utils.handleException(ex, null);
    }
  }

  // void checkScreenMode() {
  //   WidgetsBinding.instance.addPostFrameCallback((_) async {
  //     if (MediaQuery.of(context).orientation == Orientation.portrait) {
  //       await showDialog(
  //         context: context,
  //         barrierColor: ColorConsts.secondaryWhite.withOpacity(0.8),
  //         builder: (BuildContext context) => GeneralDialog(),
  //       );
  //     }
  //     showWelcomeVideoDialog();
  //   });
  // }
  //
  // SharedPreferences prefs;
  //
  // void showWelcomeVideoDialog() async {
  //   prefs = await SharedPreferences.getInstance();
  //   String permLink = "-PqP0BCiTlE";
  //   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: ColorConsts.secondaryWhite.withOpacity(0.8),
  //     builder: (BuildContext context) => VideoPlayerWidget(permLink),
  //   );
  // }

  Future<void> getTangheemTypes() async {
    try {
      _tangheemType = await TangheemUserApiClient().getTangheemType();
      if ((_tangheemType?.data?.length ?? 0) > 0) {
        _tangheemType.data.sort((a, b) => a.orderNo.compareTo(b.orderNo));
      }
      _tangheemListNotifier.value = _tangheemType?.data?.where((element) => element.isActive)?.toList()?.map((element) => element.tangheemTypeName)?.toList() ?? [];
      return;

      // enable these lines if in future need to filter types too
      if (_surahModel.data.map((element) => element.nameAR).toList().length == _surahList.length && _selectedSurah >= 0) {
        setState(() {
          _selectedTangheemType = -1;
        });
        //  filterTangheemTypesListBySurah(_surahModel.data[_selectedSurah].id, showLoading: false);
      } else {
        if (_surahModel.data.map((element) => element.nameAR).toList().length != _surahList.length && _selectedSurah >= 0) {
          setState(() {
            _selectedSurah = -1;
          });
        }
        _tangheemListNotifier.value = _tangheemType?.data?.where((element) => element.isActive)?.toList()?.map((element) => element.tangheemTypeName)?.toList() ?? [];
      }
    } catch (ex) {}
  }

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

  @override
  Widget build(BuildContext context) {
    bool isPortrait = MediaQuery.of(context).orientation == Orientation.portrait;

    return SizedBox(
      width: double.infinity,
      child: Stack(
        children: [
          Image.asset(
            "assets/icons/new/home_light.jpg",
            fit: BoxFit.cover,
            height: double.infinity,
            width: double.infinity,
            opacity: const AlwaysStoppedAnimation(.73),
          ),
          SingleChildScrollView(
            padding: isPortrait ? EdgeInsets.fromLTRB(45, 138, 45, 138) : EdgeInsets.fromLTRB(200, 45, 200, 45),
            physics: BouncingScrollPhysics(),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisSize: MainAxisSize.min,
              children: [
                Image.asset("assets/icons/new/Tangeem-logo.png", width: 126, height: 76),
                30.height,
                "موسوعة النبر والتنغيم في الأداء القرآني للأساليب اللغوية".toText(18, color: ColorConsts.darkText, textAlign: TextAlign.center),
                10.height,
                (_tangheemDiscription ?? "").toText(12, color: ColorConsts.brownColor, textAlign: TextAlign.center),
                SizedBox(height: 20),
                ValueListenableBuilder(
                  valueListenable: _tangheemListNotifier,
                  builder: (context, value, child) {
                    return CommonDropDownButton(_selectedTangheemType, hintText: "اختر الأسلوب اللغوي", list: value, onSelect: (index) {
                      if (_selectedTangheemType != index) {
                        setState(() {
                          _selectedSurah = -1;
                          _selectedTangheemType = index;
                        });
                        if (_selectedSurah >= 0) {
                          return;
                        }
                        filterSurahListByTangheemType(_tangheemListNotifier.value[_selectedTangheemType]);
                      }
                    });
                  },
                ),
                10.height,
                Row(
                  children: [
                    iconButton("بحث", "assets/icons/new/search.svg", () async {
                      // if (_selectedTangheemType < 0) {
                      //   Utils.showToast("الرجائ تعبئة جميع القوائم");
                      //   return;
                      // }
                      if (_selectedSurah < 0) {
                        Utils.showToast("يرجى اختيار السورة");
                        return;
                      }
                      _searchFocusNode.unfocus();
                      _searchFocusNode.canRequestFocus = false;
                      var surah = _surahModel.data.firstWhere((surah) => surah.nameAR == _surahList[_selectedSurah], orElse: null);
                      Map<String, Object> data = {};
                      data["surahData"] = surah;
                      if (_selectedTangheemType >= 0) {
                        data["tangheemTypeName"] = _tangheemListNotifier.value[_selectedTangheemType].toString();
                      }
                      try {
                        // await widget.analytics.logEvent(
                        //   name: 'tangheem_by_selection',
                        //   parameters: <String, dynamic>{
                        //     "tangheemTypeName": _tangheemListNotifier.value[_selectedTangheemType],
                        //     "surahName": _surahModel.data[_selectedSurah].nameAR,
                        //   },
                        // );
                      } catch (ex) {
                        print("tangheemTypeName:$ex");
                      }
                      await Navigator.pushNamed(context, TangheemScreen.routeName, arguments: data);
                      _searchFocusNode.canRequestFocus = true;
                      await getTangheemTypes();
                    }),
                    10.width,
                    Expanded(
                      child: CommonDropDownButton(_selectedSurah, hintText: "اختر السورة", list: _surahList, onSelect: (index) {
                        if (_selectedSurah != index) {
                          setState(() {
                            _selectedSurah = index;
                          });
                          if (_selectedTangheemType >= 0) {
                            return;
                          }
                          //  filterTangheemTypesListBySurah(_surahModel.data[_selectedSurah].id);
                        }
                      }),
                    )
                  ],
                ),
                20.height,
                SizedBox(
                  height: 48,
                  child: TextField(
                    controller: _searchController,
                    focusNode: _searchFocusNode,
                    style: TextStyle(color: Colors.white, fontSize: 14, fontFamily: "Montserrat"),
                    textAlign: TextAlign.end,
                    decoration: InputDecoration(
                      contentPadding: EdgeInsets.fromLTRB(2, 2, 24, 2),
                      alignLabelWithHint: true,
                      fillColor: ColorConsts.darkText.withOpacity(.65),
                      filled: true,
                      hintStyle: TextStyle(color: Colors.white, fontSize: 14, fontFamily: "Montserrat"),
                      hintText: "البحث عن آية",
                      prefixIconConstraints: BoxConstraints(maxHeight: 20),
                      prefixIcon: InkWell(
                        onTap: () async {
                          _searchFocusNode.unfocus();
                          if (_searchController.text.length < 1) {
                            Utils.showToast("الرجاء ادخال محتوى للبحث");
                            return;
                          }
                          _searchFocusNode.canRequestFocus = false;
                          var data = {"tangheemQuery": _searchController.text};
                          // await widget.analytics.setAnalyticsCollectionEnabled(true);
                          // await widget.analytics.logEvent(
                          //   name: 'tangheem_by_search',
                          //   parameters: <String, dynamic>{"tangheemQuery": _searchController.text},
                          // );
                          await Navigator.pushNamed(context, TangheemScreen.routeName, arguments: data);
                          _searchFocusNode.canRequestFocus = true;
                          await getTangheemTypes();
                        },
                        splashColor: Colors.transparent,
                        highlightColor: Colors.transparent,
                        child: SvgPicture.asset("assets/icons/new/search.svg", width: 20, height: 20, color: Colors.white).paddingOnly(left: 16, right: 8),
                      ),
                      focusedBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(10),
                        borderSide: BorderSide(color: ColorConsts.borderDarkText, width: 0),
                      ),
                      enabledBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(10),
                        borderSide: BorderSide(color: ColorConsts.borderDarkText, width: 0),
                      ),
                    ),
                  ),
                ),
                30.height,
                "شارك هذه الصفحة".toText(13, color: Color(0xffa2a2a2)),
                30.height,
                if (quickLinks != null && quickLinks.isNotEmpty)
                  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),
                    ],
                  ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  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 iconButton(String title, String icon, VoidCallback callback) {
    return InkWell(
      splashColor: Colors.transparent,
      highlightColor: Colors.transparent,
      onTap: callback,
      child: Container(
        height: 48,
        width: 70,
        decoration: BoxDecoration(
          color: callback == null ? ColorConsts.textHintGrey : ColorConsts.brownLightColor.withOpacity(.65),
          borderRadius: BorderRadius.circular(10),
        ),
        padding: EdgeInsets.all(14),
        child: SvgPicture.asset(icon, width: 20, height: 20, color: Colors.white),
      ),
    );
  }
}
