import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.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/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_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_modified_screen.dart';
import 'package:tangheem/ui/screens/tangheem_detail_screen.dart';
import 'package:tangheem/widgets/new/CommonHeader.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);
      TangheemDetailParamsModified tangheem = TangheemDetailParamsModified(selectedTangheemTypeId: ayaTangheemTypeId, ayatTangheemTypeMappedDataList: _ayatTangheemTypeMapped.data ?? []);
      Utils.hideLoading(context);
      Navigator.pushNamed(context, TangheemDetailModifiedScreen.routeName, arguments: tangheem);
    } catch (ex) {
      if (mounted) Utils.handleException(ex, null);
      Utils.hideLoading(context);
    }
  }

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

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

    Widget _header = Stack(
      alignment: Alignment.center,
      children: [
        SizedBox(
          height: isPortrait ? null : double.infinity,
          width: double.infinity,
          child: AspectRatio(
            aspectRatio: 375 / 215,
            child: Image.asset("assets/icons/new/quran_bg.jpg", fit: BoxFit.cover, alignment: Alignment(isPortrait ? -0.3 : -0.45, 0.5)),
          ),
        ),
        Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Image.asset('assets/icons/new/Tangeem-logo-W.png', width: 50),
            26.height,
            (widget.tangheemTypeName ?? "").toText(30),
            8.height,
            "${widget.surah?.nameAR ?? ""}".toText(12, color: ColorConsts.brownB6CColor),
          ],
        ).paddingOnly(top: 16),
      ],
    );

    Widget _dataListView = _dataList?.isEmpty ?? true
        ? NoDataUI().paddingOnly(top: isPortrait ? 215 : 50)
        : ListView.separated(
            controller: isPortrait ? null : _controller,
            //  physics: BouncingScrollPhysics(),
            physics: isPortrait ? NeverScrollableScrollPhysics() : null,
            shrinkWrap: isPortrait,
            padding: EdgeInsets.only(left: 24, right: 24, top: isPortrait ? 24 : 36, bottom: isPortrait ? 24 : 36),
            itemCount: _dataList.length,
            separatorBuilder: (context, index) {
              return SizedBox(height: 12);
            },
            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() ?? [];
                    TangheemDetailParamsModified tangheem = TangheemDetailParamsModified(selectedTangheemTypeId: removedData.ayaTangheemTypeId, ayatTangheemTypeMappedDataList: list);
                    Navigator.pushNamed(context, TangheemDetailModifiedScreen.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, 12, 12, 12),

                  decoration: BoxDecoration(
                    color: ColorConsts.brownLightECColor,
                    borderRadius: BorderRadius.circular(20),
                    border: Border.all(color: ColorConsts.brownB7Color, width: 0.35),
                  ),
                  // decoration: BoxDecoration(
                  //   color: Colors.white,
                  //   borderRadius: BorderRadius.circular(20),
                  //   border: Border.all(color: ColorConsts.greyE0Color, width: 1),
                  // ),
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Row(
                        // mainAxisSize: MainAxisSize.min,
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              SvgPicture.asset("assets/icons/new/surah_right.svg", height: 13, width: 11, color: ColorConsts.brownB7Color),
                              6.width,
                              (_dataList[index].surahNameAr).toText(12, color: ColorConsts.brownB7Color),
                              6.width,
                              SvgPicture.asset("assets/icons/new/surah_left.svg", height: 13, width: 11, color: ColorConsts.brownB7Color),
                            ],
                          ),
                          Row(  mainAxisSize: MainAxisSize.min,
                            children: [
                              Container(
                                padding: EdgeInsets.symmetric(vertical: 0, horizontal: 8),
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(15),
                                  border: Border.all(color: ColorConsts.greyB5Color, width: .5),
                                ),
                                child: Text(
                                  _dataList[index].tangheemTypeName ?? "",
                                  style: TextStyle(fontSize: 10, color: ColorConsts.brownB7Color),
                                ),
                              ),
                              8.width,
                              Text(
                                "الآية ${_dataList[index].ayatNumberInSurahs}",
                                style: TextStyle(fontSize: 12, color: ColorConsts.brownB7Color),
                              ),
                            ],
                          ),
                        ],
                      ),
                      TextHighLightLengthWidget(
                        text: _dataList[index].reverseAyatNumber(),
                        startIndex: _dataList[index].startIndex,
                        endIndex: _dataList[index].endIndex,
                        textAlign: TextAlign.start,
                        highLightColor: ColorConsts.brownB7Color,
                        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,
                      //   ),
                      // ),
                    ],
                  ),
                ),
              );
            },
          );

    return _dataList == null
        ? SizedBox()
        : isPortrait
            ? ListView(
                controller: _controller,
                //physics: BouncingScrollPhysics(),
                children: [_header, _dataListView],
              )
            : Row(
                children: [
                  Expanded(child: _header, flex: 4),
                  Expanded(child: _dataListView, flex: 6),
                ],
              );
  }
}
