import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:road24_mobile/data/repository/FinesRepository.dart';
import 'package:road24_mobile/data/response/manual_part/fines/FinesManualResponse.dart';
import 'package:road24_mobile/model/blocs/fines/fines_bloc.dart';
import 'package:road24_mobile/model/utils/Config.dart';
import 'package:road24_mobile/model/utils/styles/AppColors.dart';
import 'package:road24_mobile/model/utils/styles/AppStyles.dart';
import 'package:road24_mobile/utils/frequent_widgets.dart';
import 'package:road24_mobile/utils/extensions.dart';
import 'package:road24_mobile/view/built/i18n.dart';
import 'package:road24_mobile/view/manual/parts/fines/fines_manual.dart';
import 'package:road24_mobile/view/widgets/no_connection_screen.dart';
import 'package:url_launcher/url_launcher.dart';

import '../../../../../my_app.dart';

class ArticleDetails extends StatefulWidget {
  final String articleNumber;
  final String articleName;
  final String url;
  final int? goToPart;
  final int articleId;
  final List<Parts>? articleParts;

  const ArticleDetails({
    Key? key,
    required this.articleNumber,
    required this.articleName,
    required this.articleId,
    required this.url,
    this.articleParts,
    this.goToPart,
  }) : super(key: key);

  @override
  _ArticleDetailsState createState() => _ArticleDetailsState();
}

class _ArticleDetailsState extends State<ArticleDetails> {
  final ScrollController scrollController = ScrollController();

  List<GlobalKey> globalKeys = [];
  String textToShow = "";
  List<Parts> parts = [];

  GlobalKey<ScaffoldState> _key = GlobalKey();
  var fineBloc = FinesBloc(repository: FinesRepository());

  Map<String, Color> colors = {
    "MAB": AppColors.color2d9cdb,
    "SUD": AppColors.color27ae60,
    "KSUBD": AppColors.indicatorColor
  };

  @override
  void initState() {
    super.initState();
    getBasicCalculationAmount();
  }

  @override
  void dispose() {
    scrollController.dispose();
    fineBloc.close();
    super.dispose();
  }

  init() {
    if (widget.articleParts == null) {
      print("article id...${widget.articleId}");

      fineBloc.add(GetArticleParts(articleId: widget.articleId));

      textToShow = widget.articleNumber.getUnicodedText();
    } else
      gotoPart(widget.articleParts!);
  }

  gotoPart(List<Parts> articlePartList) {
    parts.clear();
    parts.addAll(articlePartList);
    parts.sort((a, b) => a.partNumber.compareTo(b.partNumber));
    globalKeys.clear();
    for (int i = 0; i < parts.length; i++) {
      globalKeys.add(GlobalKey());
    }
    if (widget.goToPart != null)
      WidgetsBinding.instance?.addPostFrameCallback((_) {
        if (widget.goToPart != null &&
            globalKeys.length >= widget.goToPart! &&
            globalKeys[widget.goToPart!].currentContext != null) {
          final RenderBox renderBoxRed = globalKeys[widget.goToPart! - 1]
              .currentContext!
              .findRenderObject() as RenderBox;

          final positionRed = renderBoxRed.localToGlobal(Offset.zero);

          scrollController.animateTo(positionRed.dy - kToolbarHeight - 20,
              duration: const Duration(milliseconds: 1000),
              curve: Curves.easeIn);
        }
      });
  }

  @override
  Widget build(BuildContext context) {
    return ValueListenableBuilder<bool>(
        valueListenable: MyApp.hasInternet,
        builder: (context, bool hasInternet, _) {
          print("hasinternet...$hasInternet");
          if (hasInternet)
            return Scaffold(
              key: _key,
              backgroundColor: AppColors.appPrimaryColor,
              appBar: AppBar(
                toolbarHeight: 60.0,
                leading: Material(
                  type: MaterialType.transparency,
                  child: InkWell(
                    onTap: () {
                      Navigator.pop(context);
                    },
                    child: Container(
                      margin: const EdgeInsets.all(10.0),
                      decoration: BoxDecoration(
                        color: Color(0xffDFDFDF),
                        shape: BoxShape.circle,
                      ),
                      child: const Center(
                        child: Icon(
                          Icons.arrow_back_ios_outlined,
                          size: 20.0,
                          color: Colors.black,
                        ),
                      ),
                    ),
                  ),
                ),
                title: Text(
                  "$textToShow${S.of(context).article}",
                  style: AppStyle.textStyle().copyWith(
                      color: Colors.black,
                      fontWeight: FontWeight.w600,
                      fontSize: 21.0),
                  maxLines: 2,
                  textAlign: TextAlign.center,
                ),
              ),
              body: BlocConsumer(
                  bloc: fineBloc,
                  listener: (context, state) {
                    if (state is BasicCalculationAmount) {
                      setState(() {
                        basicCalculationAmount = state.amount;
                      });
                      init();
                    }
                  },
                  builder: (context, state) {
                    if (state is LoadingState) {
                      return const Center(child: CircularProgressIndicator());
                    } else if (state is GetFinesManualFail) {
                      String? text;
                      try {
                        text = state.exception.toString().getErrorText();
                      } catch (ex) {
                        text = state.exception.toString() + "";
                      }
                      if (_key.currentState != null)
                        Config.showSnackBar(context, text, isRed: true);
                      return Container();
                    } else
                      return _body(state);
                  }),
            );
          else
            return NoConnectionScreen(onTap: () {
              init();
            });
        });
  }

  _body(state) {
    if (state is ArticlePartsSuccessState) {
      gotoPart(state.articleParts);
    }
    return SingleChildScrollView(
      controller: scrollController,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const SizedBox(height: 16.0),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 10.0),
            child: Text(
              widget.articleName,
              style: AppStyle.textStyle().copyWith(
                  color: Color(0xff282828),
                  fontWeight: FontWeight.w700,
                  fontSize: 18.0),
              textAlign: TextAlign.center,
            ),
          ),
          const SizedBox(height: 10.0),
          ListView.separated(
              physics: NeverScrollableScrollPhysics(),
              shrinkWrap: true,
              itemBuilder: (context, index) {
                // globalKeys.add(GlobalKey());

                var comment = parts[index].fineComment;

                return Container(
                  padding: const EdgeInsets.symmetric(horizontal: 16.0),
                  color: (widget.goToPart != null &&
                          widget.goToPart == parts[index].partNumber)
                      ? Colors.red.withOpacity(0.1)
                      : Colors.transparent,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      if (globalKeys.length > index)
                        SizedBox(key: globalKeys[index], height: 22.0),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(
                            S.of(context).part(parts[index].partNumber),
                            style: AppStyle.textStyle().copyWith(
                              color: Color(0xff282828),
                              fontSize: 18.0,
                              fontWeight: FontWeight.w700,
                            ),
                          ),
                          Row(children: [
                            for (int i = 0;
                                i <
                                    parts[index]
                                        .responsibleEntity
                                        .toString()
                                        .split(",")
                                        .length;
                                i++)
                              entityWidget(parts[index]
                                  .responsibleEntity
                                  .toString()
                                  .split(",")[i]),
                          ]),
                        ],
                      ),
                      const SizedBox(height: 8.0),
                      Text(
                        parts[index].description,
                        style: AppStyle.textStyle().copyWith(
                            color: Color(0xffF858585),
                            fontWeight: FontWeight.w400,
                            fontSize: 16.0),
                      ),
                      Padding(
                        padding: const EdgeInsets.symmetric(vertical: 13.0),
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Container(
                              width: 36.0,
                              height: 36.0,
                              decoration: BoxDecoration(
                                shape: BoxShape.circle,
                                color: AppColors.colore8e8e8,
                              ),
                              child: Center(
                                child: SvgPicture.asset(
                                    'assets/svg/article_detail_hammer.svg',
                                    color: Colors.black.withOpacity(0.5),
                                    width: 30.0,
                                    height: 30.0),
                              ),
                            ),
                            const SizedBox(width: 6.0),
                            Flexible(
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                mainAxisAlignment: MainAxisAlignment.start,
                                children: [
                                  if (parts[index].fineForCitizen != null &&
                                      parts[index].fineForCitizen != "0")
                                    Text(
                                      '${S.of(context).amount_fine} ',
                                      style: AppStyle.textStyle().copyWith(
                                        color: Color(0xff282828),
                                        fontSize: 16.0,
                                        fontWeight: FontWeight.w700,
                                      ),
                                    ),
                                  (parts[index].fineForCitizen != null &&
                                          parts[index]
                                              .citizenDiscountApplicable)
                                      ? Column(
                                          crossAxisAlignment:
                                              CrossAxisAlignment.start,
                                          children: [
                                            if (parts[index].fineForCitizen !=
                                                    null &&
                                                parts[index].fineForCitizen !=
                                                    "0")
                                              Text(
                                                "${S.of(context).for_physical_face} ",
                                                style: AppStyle.textStyle()
                                                    .copyWith(
                                                  color: Color(0xffF858585),
                                                  fontSize: 16.0,
                                                  fontWeight: FontWeight.w400,
                                                ),
                                              ),
                                            titleWidgetWithRange(
                                              "${S.of(context).without_discount} ",
                                              parts[index].fineForCitizen,
                                            ),
                                            titleWidgetWithRange(
                                                "${S.of(context).with_discount} ",
                                                parts[index].fineForCitizen,
                                                amountRatio: 0.7),
                                          ],
                                        )
                                      : (parts[index].fineForCitizen != null &&
                                              parts[index].fineForCitizen !=
                                                  "0")
                                          ? titleWidgetWithRange(
                                              "${S.of(context).for_physical_face} ",
                                              parts[index].fineForCitizen)
                                          : SizedBox(),
                                  (parts[index].fineForOfficial != null &&
                                          parts[index]
                                                  .officialDiscountApplicable ==
                                              true)
                                      ? Column(
                                          crossAxisAlignment:
                                              CrossAxisAlignment.start,
                                          children: [
                                            Text(
                                              "${S.of(context).for_official_face} ",
                                              style:
                                                  AppStyle.textStyle().copyWith(
                                                color: Color(0xffF858585),
                                                fontSize: 16.0,
                                                fontWeight: FontWeight.w400,
                                              ),
                                            ),
                                            titleWidgetWithRange(
                                              "${S.of(context).without_discount} ",
                                              // "${S.of(context).with_discount} ",
                                              parts[index].fineForOfficial,
                                            ),
                                            titleWidgetWithRange(
                                                "${S.of(context).with_discount} ",
                                                parts[index].fineForOfficial,
                                                amountRatio: 0.7),
                                          ],
                                        )
                                      : (parts[index].fineForOfficial != null)
                                          ? titleWidgetWithRange(
                                              "${S.of(context).for_official_face} ",
                                              parts[index].fineForOfficial)
                                          : SizedBox(),
                                  if (comment != null)
                                    Column(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: [
                                        Text(
                                          S.of(context).what_threatens,
                                          style: AppStyle.textStyle().copyWith(
                                            color: Color(0xff282828),
                                            fontSize: 15.0,
                                            fontWeight: FontWeight.w700,
                                          ),
                                        ),
                                        Text(
                                          comment,
                                          style: AppStyle.textStyle().copyWith(
                                            color: Color(0xffF51A51),
                                            fontSize: 16.0,
                                            fontWeight: FontWeight.w700,
                                          ),
                                          maxLines: 3,
                                        ),
                                      ],
                                    ),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
                      (index != parts.length - 1)
                          ? Divider(color: AppColors.colorcacaca, height: 1.0)
                          : SizedBox(height: 1.0),
                    ],
                  ),
                );
              },
              separatorBuilder: (context, state) =>
                  Divider(color: AppColors.colorcacaca, height: 1.0),
              itemCount: parts.length),
          Align(
            alignment: Alignment.centerRight,
            child: InkWell(
              onTap: () => launch(widget.url),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.end,
                mainAxisSize: MainAxisSize.min,
                children: [
                  SizedBox(width: 5.0),
                  Text(
                    S.of(context).more_in_lex,
                    style: AppStyle.textStyle().copyWith(
                      fontWeight: FontWeight.w600,
                      fontSize: 18.0,
                      color: Color(0xff536AEE),
                    ),
                  ),
                  SizedBox(width: 13.0),
                  Icon(
                    Icons.chevron_right,
                    size: 19.0,
                    color: AppColors.indicatorColor,
                  ),
                ],
              ),
            ),
          ),
          SizedBox(height: 60.0),
        ],
      ),
    );
  }

  entityWidget(String responsibleEntity) {
    return Container(
      height: 24.0,
      padding: EdgeInsets.symmetric(horizontal: 8.0),
      margin: EdgeInsets.only(right: 10.0),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(8.0),
        border: Border.all(
          width: 1.0,
          color: colors[responsibleEntity]!,
        ),
        color: colors[responsibleEntity]!.withOpacity(0.16),
      ),
      child: Center(
        child: Text(
          responsibleEntity,
          style: TextStyle(
            fontFamily: 'SF Pro',
            fontStyle: FontStyle.normal,
            fontSize: 14,
            letterSpacing: -0.27,
            height: 1.4,
            fontWeight: FontWeight.w600,
            color: colors[responsibleEntity],
          ),
          textAlign: TextAlign.center,
        ),
      ),
    );
  }

  getBasicCalculationAmount() async {
    if (FinesManual.basicCalculationAmount != null) {
      basicCalculationAmount = FinesManual.basicCalculationAmount!;
      init();
    } else {
      fineBloc.add(GetBasicCalculationAmount());
    }
  }

  int basicCalculationAmount = 1;
  titleWidgetWithRange(String title, String? fineForWhom,
      {double amountRatio = 1}) {
    if (fineForWhom == null) {
      init();
      return;
    }

    return TitleWidgetWithRange(
        basicCalculationAmount: basicCalculationAmount,
        context: context,
        title: title,
        fineForWhom: fineForWhom,
        amountRatio: amountRatio);
  }
}

class TitleWidgetWithRange extends StatelessWidget {
  const TitleWidgetWithRange(
      {Key? key,
      required this.basicCalculationAmount,
      required this.context,
      required this.title,
      required this.fineForWhom,
      this.amountRatio = 1})
      : super(key: key);

  final int basicCalculationAmount;
  final BuildContext context;
  final String title;
  final String fineForWhom;
  final double amountRatio;

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Flexible(
          flex: 4,
          child: Text(
            title,
            style: AppStyle.textStyle().copyWith(
              color: Color(0xffF858585),
              fontSize: 16.0,
              fontWeight: FontWeight.w400,
            ),
          ),
        ),
        Flexible(
          flex: 7,
          child: Text(
              (fineForWhom.split('-').length > 1)
                  ? "${FrequentWidgets.intComma((double.parse(fineForWhom.split('-')[0]) * basicCalculationAmount * amountRatio).toInt(), decimalDigit: 0).replaceAll(',', ' ')}-${FrequentWidgets.intComma((double.parse(fineForWhom.split('-')[1]) * basicCalculationAmount).toInt(), decimalDigit: 0).replaceAll(',', ' ')}  ${S.of(context).uzs.toLowerCase()}"
                  : "${FrequentWidgets.intComma((double.parse(fineForWhom) * basicCalculationAmount * amountRatio).toInt(), decimalDigit: 0).replaceAll(',', ' ')}  ${S.of(context).uzs.toLowerCase()}",
              style: AppStyle.textStyle().copyWith(
                  color: Color(0xffF51A51),
                  fontWeight: FontWeight.w700,
                  fontSize: 16.0),
              overflow: TextOverflow.ellipsis,
              textAlign: TextAlign.end,
              maxLines: 2),
        ),
      ],
    );
  }
}
