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/models/aya_tangheem_type.dart';
import 'package:tangheem/models/content_info_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';

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

  HomeScreen(this.analytics, {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;
  ContentInfoModel _contentInfoModel;

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

  void getSurahAndTangheemTypes() async {
    Utils.showLoading(context);
    try {
      _contentInfoModel = await TangheemUserApiClient().getContentInfo(4);
      _surahModel = await TangheemUserApiClient().getSurahs();
      AppState().setSurahModel(_surahModel);
      _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) {
    return SizedBox(
      width: double.infinity,
      child: SingleChildScrollView(
        padding: EdgeInsets.fromLTRB(16, 16, 16, 0),
        physics: BouncingScrollPhysics(),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(
              "موسوعة النبر و التنغيم في الأداء القرآني",
              style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20, color: ColorConsts.primaryBlue, height: 1),
            ),
            SizedBox(height: 4),
            Text(
              "للأساليب اللغوية",
              style: TextStyle(fontSize: 20, color: ColorConsts.primaryBlue, height: 1),
            ),
            SizedBox(height: 8),
            Text(
              Utils.getNotNullValue(_contentInfoModel?.data ?? [], 0)?.content ?? "",
              style: TextStyle(fontSize: 14, color: ColorConsts.textGrey, height: 1.5),
            ),
            SizedBox(height: 32),
            Row(
              children: [
                Expanded(
                  child: 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]);
                        }
                      });
                    },
                  ),
                ),
                SizedBox(width: 8),
                Expanded(
                  child: CommonDropDownButton(_selectedSurah, hintText: "اختر السورة", list: _surahList, onSelect: (index) {
                    if (_selectedSurah != index) {
                      setState(() {
                        _selectedSurah = index;
                      });
                      if (_selectedTangheemType >= 0) {
                        return;
                      }
                      //  filterTangheemTypesListBySurah(_surahModel.data[_selectedSurah].id);
                    }
                  }),
                )
              ],
            ),
            SizedBox(height: 16),
            Row(
              children: [
                iconButton("بحث", "assets/icons/go_forward.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();
                }),
                SizedBox(width: 8),
                iconButton(
                    "إلغاء",
                    "assets/icons/cancel.svg",
                    (_selectedSurah == -1 && _selectedTangheemType == -1)
                        ? null
                        : () {
                            _selectedSurah = -1;
                            _selectedTangheemType = -1;
                            _surahList = _surahModel.data.map((element) => element.nameAR).toList();
                            _tangheemListNotifier.value = _tangheemType?.data?.where((element) => element.isActive)?.toList()?.map((element) => element.tangheemTypeName)?.toList() ?? [];
                            setState(() {});
                          }),
              ],
            ),
            SizedBox(height: 16),
            Container(
              height: 50,
              padding: EdgeInsets.only(top: 4, bottom: 6),
              child: TextField(
                controller: _searchController,
                focusNode: _searchFocusNode,
                style: TextStyle(color: ColorConsts.primaryBlack, fontSize: 14),
                decoration: InputDecoration(
                  contentPadding: EdgeInsets.fromLTRB(4, 4, 4, 4),
                  alignLabelWithHint: true,
                  fillColor: Colors.white,
                  filled: true,
                  hintStyle: TextStyle(color: ColorConsts.textHintGrey, fontSize: 12),
                  hintText: "البحث عن آية",
                  prefixIconConstraints: BoxConstraints(maxHeight: 16),
                  prefixIcon: Padding(
                    padding: EdgeInsets.only(right: 6),
                    child: SvgPicture.asset("assets/icons/search.svg"),
                  ),
                  suffixIcon: 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: Container(
                      alignment: Alignment.center,
                      width: 80,
                      child: Text(
                        "بحث",
                        style: TextStyle(fontSize: 14, color: Colors.white),
                      ),
                      decoration: BoxDecoration(
                        color: ColorConsts.secondaryPink,
                        borderRadius: BorderRadius.only(
                          bottomLeft: Radius.circular(6),
                          topLeft: Radius.circular(6),
                        ),
                      ),
                    ),
                  ),
                  border: OutlineInputBorder(borderRadius: BorderRadius.circular(6), borderSide: BorderSide.none),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }

  Widget iconButton(String title, String icon, VoidCallback callback) {
    return InkWell(
      splashColor: Colors.transparent,
      highlightColor: Colors.transparent,
      onTap: callback,
      child: Container(
        height: 36,
        decoration: BoxDecoration(
          color: callback == null ? ColorConsts.textHintGrey : ColorConsts.secondaryPink,
          borderRadius: BorderRadius.circular(6),
        ),
        padding: EdgeInsets.fromLTRB(8, 2, 8, 2),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(
              title,
              maxLines: 1,
              style: TextStyle(fontSize: 12, color: Colors.white),
            ),
            SizedBox(width: 12),
            SvgPicture.asset(icon, width: 20, height: 20, color: Colors.white),
          ],
        ),
      ),
    );
  }
}
