import 'dart:io';
import 'dart:typed_data';
import 'dart:ui' as ui;

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:path_provider/path_provider.dart';
import 'package:share/share.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:tangheem/api/admin_configuration_api_client.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_mapped.dart';
import 'package:tangheem/models/discussion_model.dart';
import 'package:tangheem/ui/dialogs/discussion_input_dialog.dart';
import 'package:tangheem/widgets/aya_player_widget.dart';
import 'package:tangheem/widgets/aya_record_widget.dart';
import 'package:tangheem/widgets/new/CommonHeader.dart';
import 'package:tangheem/widgets/text_highlight_widget.dart';

import 'login_screen.dart';

class TangheemDetailParamsModified {
  final String selectedTangheemTypeId;
  final List<AyatTangheemTypeMappedData> ayatTangheemTypeMappedDataList;

  TangheemDetailParamsModified({@required this.selectedTangheemTypeId, @required this.ayatTangheemTypeMappedDataList});
}

class TangheemDetailModifiedScreen extends StatefulWidget {
  static const String routeName = "/tangheem_detail-modified";
  final TangheemDetailParamsModified tangheemDetailParamsModified;

  TangheemDetailModifiedScreen({Key key, this.tangheemDetailParamsModified}) : super(key: key);

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

class _TangheemDetailScreenState extends State<TangheemDetailModifiedScreen> {
  GlobalKey _globalKey = GlobalKey();

  List<VoiceNote> voiceNoteList = [];
  List<AyatTangheemTypeMappedData> ayatTangheemTypeMappedDataList = [];
  List<AyatTangheemTypeMappedData> _allDataList = [];
  List<AyatTangheemTypeMappedData> _currentDataList = [];
  List<AyatTangheemTypeMappedData> _otherDataList = [];

  int _discussionPage = -1;
  AyatTangheemTypeMappedData _ayatTangheemTypeMappedFirstData;
  DiscussionModel _discussionModel;
  bool showAyaPlayer = false;

  bool _isloading = false;

  @override
  void initState() {
    super.initState();
    _isloading = true;
    ayatTangheemTypeMappedDataList = widget.tangheemDetailParamsModified.ayatTangheemTypeMappedDataList;
    _ayatTangheemTypeMappedFirstData = ayatTangheemTypeMappedDataList.first;
    getData();
  }

  int fontSize = 18;
  SharedPreferences prefs;

  void getData() async {
    Utils.showLoading(context);
    try {
      var list = await Future.wait([
        TangheemUserApiClient().getDiscussionByTangheemID(_discussionPage, widget.tangheemDetailParamsModified.selectedTangheemTypeId),
        TangheemUserApiClient().getAyaTangheemTypeMappedRelated(_ayatTangheemTypeMappedFirstData.surahNo, _ayatTangheemTypeMappedFirstData.ayatNumberInSurahs,
            tangheemTypeId: _ayatTangheemTypeMappedFirstData.tangheemTypeId),
        TangheemUserApiClient().getAyaTangheemTypeMappedRelated(_ayatTangheemTypeMappedFirstData.surahNo, _ayatTangheemTypeMappedFirstData.ayatNumberInSurahs),
        SharedPreferences.getInstance(),
      ]);

      _discussionModel = list[0];
      AyatTangheemTypeMapped data = list[1];
      _currentDataList = data?.data ?? [];

      data = list[2];
      _allDataList = data?.data ?? [];
      prefs = list[3];
      fontSize = (prefs.getInt(GlobalConsts.fontZoomSizeTangheem) ?? 18);

      _allDataList.forEach((element) {
        if (element.tangheemTypeId != _ayatTangheemTypeMappedFirstData.tangheemTypeId) {
          _otherDataList.add(element);
        }
      });

      if (_otherDataList.isNotEmpty) {
        var seen = Set<String>();
        _otherDataList = _otherDataList.where((element) => seen.add(element.tangheemTypeId)).toList();
      }
      filterVoiceListData();
      Utils.hideLoading(context);
      _isloading = false;
      setState(() {});
    } catch (ex) {
      if (mounted) Utils.handleException(ex, null);
      Utils.hideLoading(context);
    }
  }

  void getPrefs() async {
    prefs = await SharedPreferences.getInstance();
    fontSize = (prefs.getInt(GlobalConsts.fontZoomSizeTangheem) ?? 18);
    setState(() {});
  }

  String getArabicIndexWord(int index) {
    if (index == 0) {
      return 'الأولى';
    } else if (index == 1) {
      return 'الثانية';
    } else if (index == 2) {
      return 'الثالثة';
    } else if (index == 3) {
      return 'الرابعة';
    } else if (index == 4) {
      return 'الخامسة';
    }
    return "";
  }

  void sendComment(String discussionText) async {
    Utils.showLoading(context);
    try {
      await AdminConfigurationApiClient().addDiscussion(discussionText, _ayatTangheemTypeMappedFirstData.ayaTangheemTypeId);
      Utils.showToast("تم إرسال التعليق ، سيكون مرئيًا بمجرد موافقة المسؤول عليه");
      Utils.hideLoading(context);
      Navigator.pop(context);
    } catch (ex) {
      if (mounted) Utils.handleException(ex, null);
      Utils.hideLoading(context);
    }
  }

  void filterVoiceListData() {
    _currentDataList.forEach((element) {
      voiceNoteList.addAll(element?.voiceNote ?? []);
    });
  }

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

  @override
  Widget build(BuildContext context) {
    if (_isloading) return SizedBox();

    bool isPortrait = MediaQuery.of(context).orientation == Orientation.portrait;
    Widget _header = SizedBox(
      height: isPortrait ? null : double.infinity,
      width: double.infinity,
      child: CommonHeader(_ayatTangheemTypeMappedFirstData.tangheemTypeName ?? "", "assets/icons/new/quran_bg.jpg", Color(0xffAE8646),
          isCustom: true, message: _ayatTangheemTypeMappedFirstData.tangheemTypeDescription ?? "", onTap: (headerEnum) {
        if (headerEnum == CommonHeaderEnum.ShareAsText) {
          _shareAyaAsLink();
        } else if (headerEnum == CommonHeaderEnum.ShareAsImage) {
          _shareAyaAsImage();
        } else if (headerEnum == CommonHeaderEnum.ZoomOut) {
          if (fontSize <= 12) {
            Utils.showToast("وصل حجم الخط إلى الحد الأدنى للحجم");
            return;
          }
          fontSize -= 2;
          prefs.setInt(GlobalConsts.fontZoomSize, fontSize);
          setState(() {});
        } else if (headerEnum == CommonHeaderEnum.ZoomIn) {
          if (fontSize >= 36) {
            Utils.showToast("وصل حجم الخط إلى الحد الأقصى للحجم");
            return;
          }
          fontSize += 2;
          prefs.setInt(GlobalConsts.fontZoomSize, fontSize);
          setState(() {});
        }
      }),
    );

    Widget _dataListView = SingleChildScrollView(
      physics: NeverScrollableScrollPhysics(),
      child: RepaintBoundary(
        key: _globalKey,
        child: Material(
          color: ColorConsts.greyF4Color,
          child: ListView.builder(
            physics: NeverScrollableScrollPhysics(),
            shrinkWrap: true,
            padding: EdgeInsets.only(top: 24, bottom: 24),
            itemCount: _currentDataList.length > 5 ? 5 : _currentDataList.length,
            itemBuilder: (context, index) {
              final _ayatTangheemTypeMappedData = _currentDataList[index];
              _ayatTangheemTypeMappedData.property?.sort((a, b) => a.orderNo.compareTo(b.orderNo));
              List<TangheemProperty> _tangheemInsideTableList = [];
              List<TangheemProperty> _tangheemAboveTableList = [];
              List<TangheemProperty> _tangheemBelowTableList = [];
              List<String> _tangheemWords = [];

              List<TangheemProperty> _tempPropertyList = [];
              _tempPropertyList.addAll(_ayatTangheemTypeMappedData?.property ?? <TangheemProperty>[]);
              int firstIndex = _tempPropertyList.indexWhere((element) => element.isInsideTable);

              if (firstIndex >= 0) {
                var _tempPropertyListTop = _tempPropertyList.take(firstIndex);
                _tempPropertyListTop = _tempPropertyListTop.where((element) => (element.propertyValue ?? "").isNotEmpty)?.toList() ?? [];
                _tangheemAboveTableList = _tempPropertyListTop;
                _tempPropertyListTop.forEach((element) {
                  _tempPropertyList.remove(element);
                });
                var _tempPropertyListInside = _tempPropertyList?.where((element) => (element.isInsideTable))?.toList() ?? [];
                _tempPropertyListInside.forEach((element) {
                  _tempPropertyList.remove(element);
                });
                _tempPropertyListInside = _tempPropertyListInside.where((element) => (element.propertyValue ?? "").isNotEmpty)?.toList() ?? [];
                _tangheemInsideTableList = _tempPropertyListInside;
                var _tempPropertyListBelow = _tempPropertyList;
                _tempPropertyListBelow = _tempPropertyListBelow.where((element) => (element.propertyValue ?? "").isNotEmpty)?.toList() ?? [];
                _tangheemBelowTableList = _tempPropertyListBelow;
              }

              _tangheemWords.add(_ayatTangheemTypeMappedData.highlightText ?? "");
              // _tangheemInsideTableList =
              //     _ayatTangheemTypeMappedData?.property?.where((element) => (element.isInsideTable) && (element.propertyValue ?? "").isNotEmpty)?.toList() ?? [];
              // _tangheemAboveTableList =
              //     _ayatTangheemTypeMappedData?.property?.where((element) => (!element.isInsideTable) && (element.propertyValue ?? "").isNotEmpty)?.toList() ?? [];
              //
              //

              var _tempTangheemIndexWord = "";
              if (_currentDataList.length == 1) {
                _tempTangheemIndexWord = "";
              } else {
                _tempTangheemIndexWord = getArabicIndexWord(index) + " ";
              }

              Widget innerTableWidget = (_tangheemInsideTableList.isNotEmpty)
                  ? Column(
                      children: [
                        Container(
                          height: 38,
                          width: double.infinity,
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                            color: Color(0xff40696B),
                            borderRadius: BorderRadius.only(
                              topLeft: Radius.circular(20),
                              topRight: Radius.circular(20),
                            ),
                          ),
                          child: "خط النبر و التنغيم ل${_ayatTangheemTypeMappedData.tangheemTypeName ?? ""}".toText(16),
                        ),
                        tangheemInsideTablePropertyView(_tangheemInsideTableList)
                      ],
                    )
                  : SizedBox();

              Widget aboveTableWidget = (_tangheemAboveTableList.isNotEmpty)
                  ? Container(
                      padding: EdgeInsets.only(left: 20, right: 20),
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.only(
                          topRight: Radius.circular(20),
                          topLeft: Radius.circular(20),
                        ),
                      ),
                      child: ListView.separated(
                          itemCount: _tangheemAboveTableList.length,
                          physics: NeverScrollableScrollPhysics(),
                          padding: EdgeInsets.zero,
                          shrinkWrap: true,
                          separatorBuilder: (context, index) {
                            return Divider(color: ColorConsts.greyB7Color, height: 4, thickness: 0);
                          },
                          itemBuilder: (context, index) {
                            return Row(
                              children: [
                                _tangheemAboveTableList[index].propertyText.toText(13, color: ColorConsts.greyB7Color),
                                Container(
                                  width: 1,
                                  height: 18,
                                  color: ColorConsts.greyB7Color,
                                  margin: EdgeInsets.only(left: 8, right: 8),
                                ),
                                Expanded(
                                  child: Container(
                                    padding: EdgeInsets.only(left: 4, right: 8),
                                    //   alignment: Alignment.centerRight,
                                    child: Html(
                                      data: _tangheemAboveTableList[index]?.propertyValue ?? "",
                                      style: {
                                        'html': Style(textAlign: TextAlign.left),
                                      },
                                    ),
                                  ),
                                )
                              ],
                            );
                          }),
                    )
                  : SizedBox();

              Widget belowTableWidget = (_tangheemBelowTableList.isNotEmpty) ? tangheemOutSideTablePropertyView(_tangheemBelowTableList) : SizedBox();

              Widget relatedTangheemWidget = (_allDataList.isNotEmpty)
                  ? Container(
                      width: double.infinity,
                      padding: EdgeInsets.only(top: 18, bottom: 18, left: 12, right: 12),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(20),
                        // border: Border.all(color: ColorConsts.greyE0Color, width: 1),
                      ),
                      child: Column(
                        children: [
                          "قائمة الأساليب اللغوية في هذه الآية".toText(13, color: ColorConsts.darkText),
                          12.height,
                          Wrap(
                            spacing: 8,
                            runSpacing: 8,
                            alignment: WrapAlignment.center,
                            children: [
                              for (int index = 0; index < _otherDataList.length; index++)
                                InkWell(
                                  onTap: () {
                                    List<AyatTangheemTypeMappedData> list = _otherDataList;
                                    var removedData = list[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: _allDataList[index].tangheemTypeId, ayatTangheemTypeMappedDataList: list);
                                    Navigator.pushNamed(context, TangheemDetailModifiedScreen.routeName, arguments: tangheem);
                                  },
                                  child: Container(
                                      padding: EdgeInsets.only(left: 12, right: 12, top: 6, bottom: 6),
                                      decoration: BoxDecoration(
                                        borderRadius: BorderRadius.circular(10),
                                        color: Color(0xff91C1BC),
                                      ),
                                      child: _otherDataList[index].tangheemTypeName.toText(12)),
                                ),
                            ],
                          ),
                        ],
                      ),
                    )
                  : SizedBox();

              Widget aboveInnerMerge = Container(
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(20),
                    topRight: Radius.circular(20),
                  ),
                ),
                child: Column(
                  children: [aboveTableWidget, innerTableWidget],
                ),
              );

              Widget aboveInnerBelowMerge = Container(
                decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(20), boxShadow: [BoxShadow(color: ColorConsts.greyE0Color, offset: Offset(0.0, 1.0), blurRadius: 0)]
                    //   border: Border.all(color: ColorConsts.greyE0Color, width: 1),
                    ),
                child: Column(
                  children: [aboveInnerMerge, belowTableWidget],
                ),
              );

              return ListView(
                physics: NeverScrollableScrollPhysics(),
                shrinkWrap: true,
                padding: EdgeInsets.only(top: 21, bottom: 21, left: 24, right: 24),
                children: [
                  " جملة ${_ayatTangheemTypeMappedData.tangheemTypeName} $_tempTangheemIndexWord".toText(22, color: ColorConsts.darkText, textAlign: TextAlign.center, height: 22),
                  12.height,
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      SvgPicture.asset("assets/icons/new/surah_right.svg", height: 13, width: 11, color: ColorConsts.darkText),
                      12.width,
                      _ayatTangheemTypeMappedData.surahNameAr.toText(13, color: ColorConsts.darkText, textAlign: TextAlign.center, height: 22),
                      12.width,
                      SvgPicture.asset("assets/icons/new/surah_left.svg", height: 13, width: 11, color: ColorConsts.darkText)
                    ],
                  ).center,
                  Container(
                    margin: EdgeInsets.only(top: 21, bottom: 21),
                    padding: EdgeInsets.all(12),
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(20),
                      border: Border.all(color: ColorConsts.greyE0Color, width: 1),
                    ),
                    child: TextHighLightLengthWidget(
                      text: _ayatTangheemTypeMappedData.reverseAyatNumber(),
                      startIndex: _ayatTangheemTypeMappedData.startIndex,
                      endIndex: _ayatTangheemTypeMappedData.endIndex,
                      textAlign: TextAlign.start,
                      fontSize: fontSize.toDouble(),
                      highlightAya: _ayatTangheemTypeMappedData.highlightText,
                      highlightAyaNos: _ayatTangheemTypeMappedData.highlightAyaNos ?? "",
                      ayahTextList: _ayatTangheemTypeMappedData.ayahTextList,
                    ),
                  ),
                  Container(
                    decoration: BoxDecoration(
                      color: Colors.transparent,
                      borderRadius: BorderRadius.circular(20),
                      border: Border.all(color: ColorConsts.greyE0Color, width: 1),
                    ),
                    child: Column(
                      children: [aboveInnerBelowMerge, relatedTangheemWidget],
                    ),
                  )
                ],
              );
            },
          ),
        ),
      ),
    );
    Widget _ayaPlayer = AyaPlayerWidget(
            surahName: _ayatTangheemTypeMappedFirstData?.surahNameAr ?? "",
            ayaTangheemTypeId: _ayatTangheemTypeMappedFirstData?.tangheemTypeId ?? "",
            globalKey: _globalKey,
            numberInSurah: _ayatTangheemTypeMappedFirstData?.ayatNumberInSurahs,
            ayaNo: _ayatTangheemTypeMappedFirstData?.ayahNo,
            surahNo: _ayatTangheemTypeMappedFirstData?.surahNo,
            voiceNoteList: voiceNoteList)
        .paddingOnly(left: 24, right: 24);

    return Container(
      width: double.infinity,
      child: _ayatTangheemTypeMappedFirstData == null
          ? SizedBox()
          : isPortrait
              ? ListView(
                  physics: BouncingScrollPhysics(),
                  padding: EdgeInsets.only(bottom: 16),
                  children: [
                    _header,
                    _dataListView,
                    _ayaPlayer,
                    SizedBox(height: 16),
                    AyaRecordWidget().paddingOnly(left: 24, right: 24),
                    SizedBox(height: 16),
                    discussionView(_discussionModel?.data ?? []).paddingOnly(left: 24, right: 24),
                    SizedBox(height: 16),
                  ],
                )
              : Row(
                  children: [
                    Expanded(child: _header, flex: 4),
                    Expanded(
                        child: ListView(
                          physics: BouncingScrollPhysics(),
                          children: [
                            _dataListView,
                            _ayaPlayer,
                            SizedBox(height: 16),
                            AyaRecordWidget().paddingOnly(left: 24, right: 24),
                            SizedBox(height: 16),
                            discussionView(_discussionModel?.data ?? []).paddingOnly(left: 24, right: 24),
                            SizedBox(height: 16),
                          ],
                        ),
                        flex: 6),
                  ],
                ),
    );
  }

  Widget nextOptionButton(String icon, String text, VoidCallback onPressed) {
    return InkWell(
      onTap: onPressed,
      child: onPressed == null
          ? SizedBox()
          : Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisSize: MainAxisSize.min,
              children: [
                SvgPicture.asset(icon, height: 12, width: 12),
                SizedBox(width: 4),
                Text(
                  text,
                  style: TextStyle(color: ColorConsts.textGrey),
                ),
              ],
            ),
    );
  }

  Widget previousOptionButton(String icon, String text, VoidCallback onPressed) {
    return InkWell(
      onTap: onPressed,
      child: onPressed == null
          ? SizedBox()
          : Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(
                  text,
                  style: TextStyle(color: ColorConsts.textGrey),
                ),
                SizedBox(width: 4),
                SvgPicture.asset(icon, height: 12, width: 12),
              ],
            ),
    );
  }

  Widget tangheemOutSideTablePropertyView(List<TangheemProperty> tangheemPropertyList) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border(
            // left: BorderSide(color: ColorConsts.greyE0Color, width: 1),
            // right: BorderSide(color: ColorConsts.greyE0Color, width: 1),
            // bottom: BorderSide(color: ColorConsts.greyE0Color, width: 1),
            // top: BorderSide(color: ColorConsts.greyE0Color, width: 1),
            ),
        borderRadius: BorderRadius.only(
          bottomLeft: Radius.circular(20),
          bottomRight: Radius.circular(20),
        ),
      ),
      child: ListView.separated(
          itemCount: tangheemPropertyList.length,
          physics: NeverScrollableScrollPhysics(),
          padding: EdgeInsets.only(left: 20, right: 20),
          shrinkWrap: true,
          separatorBuilder: (context, index) {
            return Divider(color: ColorConsts.greyB7Color, height: 1, thickness: 0);
          },
          itemBuilder: (context, index) {
            return Row(
              children: [
                tangheemPropertyList[index].propertyText.toText(13, color: ColorConsts.greyB7Color),
                Container(
                  width: 1,
                  height: 18,
                  color: ColorConsts.greyB7Color,
                  margin: EdgeInsets.only(left: 8, right: 8),
                ),
                Expanded(
                  child: Container(
                    padding: EdgeInsets.only(left: 4, right: 8),
                    //  alignment: Alignment.centerRight,
                    child: Html(
                      data: tangheemPropertyList[index]?.propertyValue ?? "",
                      style: {
                        'html': Style(textAlign: TextAlign.left),
                      },
                    ),
                  ),
                )
              ],
            );
          }),
    );
  }

  Widget tangheemInsideTablePropertyView(List<TangheemProperty> tangheemPropertyList) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        for (var property in tangheemPropertyList)
          Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Container(
                height: 35,
                width: double.infinity,
                color: Color(0xff669A9D),
                alignment: Alignment.center,
                child: (property.propertyText ?? "").toText(16),
              ),
              Container(
                width: double.infinity,
                decoration: BoxDecoration(
                    color: Colors.white,
                    border: Border(
                      top: BorderSide(color: ColorConsts.greyE0Color, width: 1),
                      bottom: BorderSide(color: ColorConsts.greyE0Color, width: 1),
                    )),
                padding: EdgeInsets.all(4),
                child: Html(
                  data: property.propertyValue ?? "",
                  style: {
                    'html': Style(textAlign: TextAlign.left),
                  },
                ),
              ),
            ],
          ),
      ],
    );
  }

  Widget discussionView(List<DiscussionModelData> _discussionList) {
    _discussionList = _discussionList.where((element) => element.status.toLowerCase() == "Accept".toLowerCase()).toList();
    return Stack(
      alignment: Alignment.bottomCenter,
      children: [
        Container(
          margin: EdgeInsets.only(top: 4, bottom: 25),
          padding: EdgeInsets.all(0),
          width: double.infinity,
          decoration: BoxDecoration(
            color: Colors.transparent,
            borderRadius: BorderRadius.circular(20),
            border: Border.all(color: ColorConsts.greyE0Color, width: 1),
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Container(
                height: 38,
                width: double.infinity,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  color: ColorConsts.brownB1CColor,
                  borderRadius: BorderRadius.only(
                    topRight: Radius.circular(20.0),
                    topLeft: Radius.circular(20.0),
                  ),
                ),
                child: "التعليقات".toText(16),
              ),
              _discussionList.isNotEmpty
                  ? ListView.separated(
                      padding: EdgeInsets.only(top: 4, bottom: 24, left: 8, right: 8),
                      shrinkWrap: true,
                      physics: NeverScrollableScrollPhysics(),
                      itemCount: _discussionList.length,
                      separatorBuilder: (context, index) => Divider(height: 1, thickness: 1, color: ColorConsts.greyE0Color).paddingOnly(top: 12, bottom: 12),
                      itemBuilder: (context, index) {
                        return Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Row(
                              children: [
                                SvgPicture.asset(
                                  "assets/icons/chat_user.svg",
                                  width: 60,
                                  height: 60,
                                ),
                                SizedBox(width: 8),
                                Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    "تعليق على الآية ${_ayatTangheemTypeMappedFirstData.ayatNumberInSurahs}".toText(16, color: ColorConsts.primaryBlue, isBold: true),
                                    SizedBox(height: 4),
                                    Directionality(
                                      textDirection: TextDirection.ltr,
                                      child: _discussionList[index].date.toFormattedDate().toText(12, color: ColorConsts.textGrey),
                                    ),
                                  ],
                                ),
                              ],
                            ),
                            SizedBox(height: 4),
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                ("تعليق من: " + _discussionList[index].userName).toText(14, isBold: true, color: ColorConsts.primaryBlue),
                                _discussionList[index].discussionText.toText(14, color: ColorConsts.textGrey),
                                if ((_discussionList[index]?.adminResponse ?? "").isNotEmpty) SizedBox(height: 4),
                                if ((_discussionList[index]?.adminResponse ?? "").isNotEmpty) ("رد من المسؤول: " + _discussionList[index].adminResponse).toText(14, color: ColorConsts.textGrey),
                              ],
                            )
                          ],
                        );
                      },
                    )
                  : "لا يوجد تعليقات".toText(14, color: ColorConsts.primaryBlue).paddingOnly(bottom: 24, top: 12),
            ],
          ),
        ),
        Positioned(
          bottom: 0,
          child: InkWell(
            borderRadius: BorderRadius.circular(30),
            onTap: () async {
              if (!AppState().isUserLogin) {
                Widget cancelButton = Container(
                        height: 40,
                        padding: EdgeInsets.only(left: 16, right: 16),
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(30),
                          color: ColorConsts.darkText,
                        ),
                        child: "أرغب بالتسجيل".toText(14, fontFamily: false))
                    .onPress(() async {
                  Navigator.pop(context);
                  await Navigator.pushNamed(context, LoginScreen.routeName);
                  if (!AppState().isUserLogin) {
                    return;
                  }
                });

                Widget continueButton = Container(
                        height: 40,
                        padding: EdgeInsets.only(left: 16, right: 16),
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(30),
                          color: ColorConsts.darkText,
                        ),
                        child: "استمرار كضيف".toText(14, fontFamily: false))
                    .onPress(() {
                  Navigator.pop(context);
                  return;
                });

                AlertDialog alert = AlertDialog(
                  content: "هذه الخاصية متاحه فقط للأعضاء المسجلين".toText(18, color: ColorConsts.darkText, isBold: true, fontFamily: false),
                  actionsAlignment: MainAxisAlignment.spaceEvenly,
                  shape: const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(24.0))),
                  actions: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        cancelButton,
                        continueButton,
                      ],
                    ),
                  ],
                );
                showDialog(
                  context: context,
                  builder: (BuildContext context) {
                    return alert;
                  },
                );

                return;
              }
              showDialog(
                context: context,
                barrierColor: ColorConsts.secondaryWhite.withOpacity(0.8),
                builder: (BuildContext context) => DiscussionInputDialog(onCommentPress: (comment) {
                  sendComment(comment);
                }),
              );
            },
            child: Container(
                height: 40,
                padding: EdgeInsets.only(left: 28, right: 28),
                alignment: Alignment.centerRight,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(30),
                  color: ColorConsts.greenLightColor,
                ),
                child: "إضافة تعليق".toText(14)),
          ),
        ),
      ],
    );
  }

  void _shareAyaAsLink() async {
    String _url =
        "${ApiConsts.baseUrl}/quran/tangheemtype?surahNo=${_ayatTangheemTypeMappedFirstData?.surahNo}&ayahNo=${_ayatTangheemTypeMappedFirstData?.ayahNo}&tanghemType=${_ayatTangheemTypeMappedFirstData?.tangheemTypeId}&numberinsurah=${_ayatTangheemTypeMappedFirstData?.ayatNumberInSurahs}";
    await Share.share(_url);
  }

  void _shareAyaAsImage() async {
    Utils.showLoading(context);
    try {
      RenderRepaintBoundary boundary = _globalKey.currentContext.findRenderObject();
      ui.Image image = await boundary.toImage(pixelRatio: 3.0);
      ByteData byteData = await image.toByteData(format: ui.ImageByteFormat.png);
      Uint8List pngBytes = byteData.buffer.asUint8List();

      final tempDir = await getTemporaryDirectory();
      final file = await File('${tempDir.path}/${DateTime.now().toString()}.png').create();
      await file.writeAsBytes(pngBytes);
      await TangheemUserApiClient().addStatistics(3);
      await Share.shareFiles(['${file.path}']);
      Utils.hideLoading(context);
    } catch (ex) {
      Future.delayed(Duration(seconds: 1), () {
        Utils.hideLoading(context);
      });
    }
  }

  Widget zoomButtons(String icon, VoidCallback onPressed, {double size, bool isAsset = true}) {
    return IconButton(
      highlightColor: Colors.transparent,
      splashColor: Colors.transparent,
      constraints: BoxConstraints(),
      padding: EdgeInsets.only(right: 2),
      icon: SvgPicture.asset(icon, height: size ?? 20, width: size ?? 20),
      onPressed: onPressed,
    );
  }
}
