import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.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/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 AddNewCarLawPage extends StatefulWidget {
  const AddNewCarLawPage({Key? key}) : super(key: key);
  @override
  _AddNewCarLawPageState createState() => _AddNewCarLawPageState();
}

class _AddNewCarLawPageState extends State<AddNewCarLawPage> {
  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).my_car),
                  body: BlocListener(
                    bloc: bloc,
                    listener: (context, state) {
                      if (state is MustKnowSuccessState) {
                        if (mounted)
                          setState(() {
                            data = state.response.avtoContent;
                          });
                      } else if (state is FaqsLoadingState) {
                        setState(() {});
                      } 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
                        ? _buildCarLawPage(context, data!)
                        : Center(
                            child: CircularProgressIndicator(),
                          ),
                  ),
                  bottomSheet: _BottomSheet(),
                )
              : NoConnectionScreen(onTap: () {
                  Navigator.pushReplacement(
                      context, FadeRoute(page: AddNewCarLawPage()));
                });
        });
  }

  _Body _buildCarLawPage(BuildContext context, String data) {
    return _Body(
      data: data,
      onTapLink: () {
        Navigator.push(
          context,
          CupertinoPageRoute(builder: (_) => InspectionManual()),
        );
      },
    );
  }
}

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 onTapLink;
  final String data;

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

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

class _BottomSheet extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      height: 100,
      alignment: Alignment.bottomCenter,
      padding: EdgeInsets.only(bottom: 30),
      color: AppColors.appPrimaryColor,
      child: GestureDetector(
        onTap: () => Navigator.pop(context),
        child: Container(
          width: double.infinity,
          height: 60,
          margin: EdgeInsets.symmetric(horizontal: 16),
          padding: 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,
            ),
          ),
        ),
      ),
    );
  }
}
