import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:flutter_html/html_parser.dart';
import 'package:flutter_html/style.dart';
import 'package:road24_mobile/data/repository/FaqRepository.dart';
import 'package:road24_mobile/model/blocs/faq/faq_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/view/built/i18n.dart';
import 'package:road24_mobile/utils/extensions.dart';
import 'package:road24_mobile/view/manual/parts/fines/fines_manual.dart';
import 'package:road24_mobile/view/manual/parts/inspection/inspection_manual.dart';
import 'package:road24_mobile/view/widgets/fade_route.dart';
import 'package:road24_mobile/view/widgets/no_connection_screen.dart';

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

class InspectionMustKnow extends StatefulWidget {
  const InspectionMustKnow({Key? key}) : super(key: key);
  @override
  _InspectionMustKnowState createState() => _InspectionMustKnowState();
}

class _InspectionMustKnowState extends State<InspectionMustKnow> {
  var bloc = FAQBloc(repository: FAQRepository());
  GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  String? data;
  @override
  void initState() {
    super.initState();
    bloc.add(GetMustKnowText());
  }

  @override
  Widget build(BuildContext context) {
    return ValueListenableBuilder(
        valueListenable: MyApp.hasInternet,
        builder: (context, bool hasInternet, _) {
          return (hasInternet)
              ? Scaffold(
                  key: _scaffoldKey,
                  backgroundColor: AppColors.appPrimaryColor,
                  appBar:
                      _AppBar(titleText: S.of(context).technical_inspection),
                  body: BlocListener(
                    bloc: bloc,
                    listener: (context, state) {
                      if (state is MustKnowSuccessState) {
                        setState(() {
                          data = state.response.texosmotrContent;
                        });
                      } else if (state is FaqsLoadingState) {
                      } else if (state is FaqsError) {
                        String text = "";
                        try {
                          text = state.exception.toString().getErrorText();
                        } catch (ex) {
                          text = state.exception.toString();
                        }
                        Config.showSnackBar(
                          context,
                          text,
                        );
                      }
                    },
                    child: data != null
                        ? _buildMustKnowText(context, data!)
                        : Center(
                            child: CircularProgressIndicator(),
                          ),
                  ),
                  bottomSheet: _BottomSheet(),
                )
              : NoConnectionScreen(onTap: () {
                  Navigator.pushReplacement(
                      context, FadeRoute(page: const InspectionMustKnow()));
                });
        });
  }

  _Body _buildMustKnowText(BuildContext context, String data) {
    return _Body(
      data: data,
      // data: S.of(context).technical_must_text,
      onTapLinkREO: () {
        Navigator.push(
          context,
          CupertinoPageRoute(builder: (context) => InspectionManual()),
        );
      },
      onTapLinkYHQ: () {
        print('YHQ');
        Navigator.push(
          context,
          CupertinoPageRoute(builder: (context) => FinesManual()),
        );
      },
    );
  }
}

class _AppBar extends StatelessWidget implements PreferredSizeWidget {
  final String? titleText;

  const _AppBar({this.titleText});

  @override
  Widget build(BuildContext context) {
    return AppBar(
      toolbarHeight: 60.0,
      leading: FrequentWidgets.appBarBackButton(context),
      title: Text(
        "$titleText",
        style: AppStyle.textStyle().copyWith(
            color: Colors.black, fontWeight: FontWeight.w600, fontSize: 17.0),
      ),
    );
  }

  @override
  Size get preferredSize => Size.fromHeight(kToolbarHeight);
}

class _Body extends StatelessWidget {
  final GestureTapCallback onTapLinkREO;
  final GestureTapCallback onTapLinkYHQ;
  final String data;

  const _Body(
      {required this.data,
      required this.onTapLinkREO,
      required this.onTapLinkYHQ});

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      physics: BouncingScrollPhysics(),
      child: Container(
        width: double.infinity,
        margin:
            const EdgeInsets.only(left: 12, right: 12, top: 16, bottom: 130),
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(16),
        ),
        child: Html(
          data: data,
          // shrinkWrap: true,
          customRender: {
            'mylink1': (RenderContext context, Widget child) {
              //  (_, it, __, ___) {
              String text = "";
              final ContainerSpan response = child as ContainerSpan;
              if (response.children!.length > 0)
                text = response.children![0].toPlainText();
              return GestureDetector(
                onTap: onTapLinkREO,
                child: Text(
                  text,
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w400,
                    color: AppColors.color2d9cdb,
                    fontFamily: 'SF Pro',
                  ),
                ),
              );
            },
            'mylink2': (context, it) {
              // (_, it, __, ___) {
              String text = "";
              final ContainerSpan response = it as ContainerSpan;
              if (response.children!.length > 0)
                text = response.children![0].toPlainText();
              return GestureDetector(
                onTap: onTapLinkYHQ,
                child: Text(
                  text,
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w400,
                    color: AppColors.color2d9cdb,
                    fontFamily: 'SF Pro',
                  ),
                ),
              );
            }
          },

          tagsList: Html.tags..addAll(["mylink1", "mylink2"]),
          style: {
            'h1': Style(
              fontSize: FontSize(18),
              fontWeight: FontWeight.w700,
              color: AppColors.colorf51a51,
              fontFamily: 'SF Pro',
            ),
            'h2': Style(
              fontSize: FontSize(18),
              fontWeight: FontWeight.w700,
              fontFamily: 'SF Pro',
            ),
            'span': Style(
              fontSize: FontSize(16),
              fontWeight: FontWeight.w400,
              color: AppColors.colorf51a51,
              fontFamily: 'SF Pro',
            ),
            'p': Style(
              fontSize: FontSize(16),
              fontWeight: FontWeight.w400,
              color: AppColors.selectedColor,
              fontFamily: 'SF Pro',
            ),
          },
        ),
      ),
    );
  }
}

class _BottomSheet extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      height: 90,
      alignment: Alignment.bottomCenter,
      padding: const EdgeInsets.only(bottom: 30),
      color: AppColors.appPrimaryColor,
      child: GestureDetector(
        onTap: () => Navigator.pop(context),
        child: Container(
          width: double.infinity,
          height: 60,
          margin: const EdgeInsets.symmetric(horizontal: 16),
          padding: const EdgeInsets.symmetric(vertical: 18),
          alignment: Alignment.center,
          decoration: BoxDecoration(
            color: AppColors.selectedColor,
            borderRadius: BorderRadius.circular(12),
          ),
          child: Text(
            S.of(context).back,
            style: AppStyle.textStyle().copyWith(
              color: Colors.white,
              fontSize: 16,
              fontWeight: FontWeight.w600,
            ),
          ),
        ),
      ),
    );
  }
}
