import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:tangheem/api/tangheem_user_api_client.dart';
import 'package:tangheem/classes/colors.dart';
import 'package:tangheem/classes/utils.dart';
import 'package:tangheem/models/aya_tangheem_type_mapped.dart';
import 'package:tangheem/models/surah_model.dart';
import 'package:tangheem/ui/misc/no_data_ui.dart';
import 'package:tangheem/ui/screens/tangheem_detail_screen.dart';
import 'package:tangheem/widgets/text_highlight_widget.dart';

class TangheemScreen extends StatefulWidget {
  static const String routeName = "/tangheem";
  final String tangheemQuery;
  final String tangheemTypeName;
  final SurahModelData surah;

  TangheemScreen({Key key, this.surah, this.tangheemQuery, this.tangheemTypeName}) : super(key: key);

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

class _TangheemScreenState extends State<TangheemScreen> {
  AyatTangheemTypeMapped _ayatTangheemTypeMapped;
  List<AyatTangheemTypeMappedData> _dataList;
  final int itemsPerPage = 10;
  int currentPageNo = 1;
  ScrollController _controller;
  bool canCallApi = false;

  @override
  void initState() {
    super.initState();
    _controller = new ScrollController()..addListener(_scrollListener);
    if (widget.tangheemQuery == null) {
      getTangheemData();
    } else {
      getTangheemDataByKeyword();
    }
  }

  _scrollListener() {
    if (_controller.position.extentAfter.toInt() <= 0 && canCallApi) {
      if (_dataList.length < _ayatTangheemTypeMapped.totalItemsCount) {
        currentPageNo++;
        if (widget.tangheemQuery == null) {
          getTangheemData();
        } else {
          getTangheemDataByKeyword();
        }
      }
      canCallApi = false;
    }
  }

  void getTangheemDataByKeyword() async {
    Utils.showLoading(context);
    try {
      _ayatTangheemTypeMapped = await TangheemUserApiClient().ayahBaseTextGet(widget.tangheemTypeName, widget.tangheemQuery, itemsPerPage, currentPageNo);
      _dataList = (_dataList ?? <AyatTangheemTypeMappedData>[]) + (_ayatTangheemTypeMapped?.data ?? <AyatTangheemTypeMappedData>[]);
    } catch (ex) {
      _dataList = _dataList ?? <AyatTangheemTypeMappedData>[];
      if (mounted) Utils.handleException(ex, null);
    } finally {
      Utils.hideLoading(context);
      canCallApi = true;
    }
    setState(() {});
  }

  void getTangheemData() async {
    Utils.showLoading(context);
    try {
      _ayatTangheemTypeMapped = await TangheemUserApiClient().getAyaTangheemTypeMapped(widget.surah?.surahID, widget.tangheemTypeName, widget.tangheemQuery, itemsPerPage, currentPageNo);
      _dataList = (_dataList ?? <AyatTangheemTypeMappedData>[]) + (_ayatTangheemTypeMapped?.data ?? <AyatTangheemTypeMappedData>[]);
    } catch (ex) {
      _dataList = _dataList ?? <AyatTangheemTypeMappedData>[];
      if (mounted) Utils.handleException(ex, null);
    } finally {
      Utils.hideLoading(context);
      canCallApi = true;
    }
    setState(() {});
  }

  void getTangheemDataForTangheem(int surahNo, String numberInSurahs, String tangheemTypeId, String ayaTangheemTypeId) async {
    Utils.showLoading(context);
    try {
      AyatTangheemTypeMapped _ayatTangheemTypeMapped = await TangheemUserApiClient().getAyaTangheemTypeMappedFor(surahNo, numberInSurahs, tangheemTypeId);
      TangheemDetailParams tangheem = TangheemDetailParams(selectedTangheemTypeId: ayaTangheemTypeId, ayatTangheemTypeMappedDataList: _ayatTangheemTypeMapped.data ?? []);
      Utils.hideLoading(context);
      Navigator.pushNamed(context, TangheemDetailScreen.routeName, arguments: tangheem);
    } catch (ex) {
      if (mounted) Utils.handleException(ex, null);
      Utils.hideLoading(context);
    }
  }

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

  @override
  Widget build(BuildContext context) {
    return _dataList == null
        ? SizedBox()
        : _dataList.isEmpty
            ? NoDataUI()
            : ListView.separated(
                controller: _controller,
                physics: BouncingScrollPhysics(),
                padding: EdgeInsets.all(16),
                itemCount: _dataList.length,
                separatorBuilder: (context, index) {
                  return SizedBox(height: 8);
                },
                itemBuilder: (context, index) {
                  return InkWell(
                    onTap: () {
                      if (widget.tangheemQuery == null) {
                        List<AyatTangheemTypeMappedData> list = <AyatTangheemTypeMappedData>[] + _dataList;
                        var removedData = _dataList[index];
                        list.remove(removedData);
                        list.insert(0, removedData);
                        list = list?.where((element) => (element.ayahNos.contains(removedData.ayahNos)) && (element.tangheemTypeId == removedData.tangheemTypeId))?.toList() ?? [];
                        TangheemDetailParams tangheem = TangheemDetailParams(selectedTangheemTypeId: removedData.ayaTangheemTypeId, ayatTangheemTypeMappedDataList: list);
                        Navigator.pushNamed(context, TangheemDetailScreen.routeName, arguments: tangheem);
                      } else {
                        var removedData = _dataList[index];
                        getTangheemDataForTangheem(removedData.surahNo, removedData.ayatNumberInSurahs, removedData.tangheemTypeId, removedData.ayaTangheemTypeId);
                      }
                    },
                    borderRadius: BorderRadius.circular(4),
                    child: Container(
                      padding: EdgeInsets.fromLTRB(12, 8, 12, 8),
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(4),
                      ),
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Text(
                                _dataList[index].surahNameAr + ":",
                                style: TextStyle(fontSize: 12, color: ColorConsts.primaryBlue),
                              ),
                              Text(
                                " ${_dataList[index].ayatNumberInSurahs}",
                                style: TextStyle(fontSize: 14, fontFamily: "BArabics", color: ColorConsts.secondaryOrange),
                              ),
                              SizedBox(width: 4),
                              Text(
                                "(${_dataList[index].tangheemTypeName})",
                                style: TextStyle(fontSize: 12, color: ColorConsts.secondaryOrange),
                              ),
                            ],
                          ),
                          TextHighLightLengthWidget(
                            text: _dataList[index].reverseAyatNumber(),
                            startIndex: _dataList[index].startIndex,
                            endIndex: _dataList[index].endIndex,
                            textAlign: TextAlign.start,
                            highlightAya: _dataList[index].highlightText,
                            highlightAyaNos: _dataList[index].highlightAyaNos ?? "",
                            ayahTextList: _dataList[index].ayahTextList,
                          ),
                          // TextHighLightWidget(
                          //   text: _dataList[index].reverseAyatNumber(),
                          //   valueColor: ColorConsts.secondaryOrange,
                          //   highlights: [_dataList[index].highlightText],
                          //   textAlign: TextAlign.start,
                          //   style: TextStyle(
                          //     fontFamily: "UthmanicHafs",
                          //     fontSize: 16,
                          //     color: ColorConsts.primaryBlue,
                          //     fontWeight: FontWeight.bold,
                          //   ),
                          // ),
                        ],
                      ),
                    ),
                  );
                },
              );
  }
}
