import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_linkify/flutter_linkify.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/styles/AppColors.dart';
import 'package:road24_mobile/model/utils/styles/AppStyles.dart';
import 'package:road24_mobile/view/built/i18n.dart';
import 'package:road24_mobile/view/widgets/fade_route.dart';
import 'package:road24_mobile/view/widgets/no_connection_screen.dart';
import 'package:url_launcher/url_launcher.dart';

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

class FAQ extends StatefulWidget {
  const FAQ({Key? key}) : super(key: key);

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

class _FAQState extends State<FAQ> {
  late FAQBloc faqbloc;

  @override
  void initState() {
    super.initState();
    faqbloc = FAQBloc(repository: FAQRepository());
    faqbloc.add(GetFAQList());
  }

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

  @override
  Widget build(BuildContext context) {
    return ValueListenableBuilder(
        valueListenable: MyApp.hasInternet,
        builder: (context, bool hasInternet, _) {
          return (hasInternet)
              ? Scaffold(
                  backgroundColor: AppColors.appPrimaryColor,
                  appBar: appBar(context),
                  body: mainScreen(),
                )
              : NoConnectionScreen(onTap: () {
                  Navigator.pushReplacement(
                    context,
                    FadeRoute(page: const FAQ()),
                  );
                });
        });
  }

  AppBar appBar(BuildContext context) {
    return AppBar(
      toolbarHeight: 60.0,
      leading: Material(
        type: MaterialType.transparency,
        child: InkWell(
          onTap: () {
            Navigator.pop(context);
          },
          child: Container(
            margin: const EdgeInsets.all(10.0),
            decoration: const 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(
        S.of(context).manual_FAQ,
        style: AppStyle.textStyle().copyWith(
            color: Colors.black, fontWeight: FontWeight.w600, fontSize: 21.0),
      ),
    );
  }

  mainScreen() {
    // for(var result in )
    return BlocBuilder(
        bloc: faqbloc,
        builder: (context, state) {
          if (state is FaqsSuccessState) {
            var list = state.response.results.reversed.toList();

            return ListView.builder(
              padding: const EdgeInsets.symmetric(horizontal: 4),
              itemCount: state.response.count,
              scrollDirection: Axis.vertical,
              shrinkWrap: true,
              physics: const BouncingScrollPhysics(),
              itemBuilder: (context, index) {
                var item = list[index];
                if (item.question != null)
                  return Container(
                    margin: const EdgeInsets.symmetric(
                        horizontal: 8.0, vertical: 6),
                    padding: const EdgeInsets.symmetric(
                        horizontal: 4.0, vertical: 4),
                    decoration: BoxDecoration(
                        boxShadow: [
                          BoxShadow(
                              offset: Offset(0, 2),
                              blurRadius: 7,
                              color: Colors.black.withOpacity(0.1))
                        ],
                        borderRadius: BorderRadius.circular(9),
                        color: Colors.white),
                    child: Theme(
                      data: Theme.of(context)
                          .copyWith(dividerColor: Colors.transparent),
                      child: ExpansionTile(
                        title: Text(
                          item.question!,
                          style: TextStyle(
                              fontSize: 16.0, fontWeight: FontWeight.w700),
                        ),
                        childrenPadding:
                            const EdgeInsets.symmetric(horizontal: 8),
                        collapsedTextColor: Colors.black.withOpacity(0.7),
                        collapsedIconColor: Colors.black.withOpacity(0.7),
                        textColor: Colors.black,
                        iconColor: Colors.black,
                        children: <Widget>[
                          ListTile(
                            title: Linkify(
                              onOpen: (link) async {
                                if (await canLaunch(link.url)) {
                                  await launch(link.url);
                                }
                              },
                              text: "${item.answer}\n",
                              style: const TextStyle(
                                  fontSize: 15.0, fontWeight: FontWeight.w400),
                            ),
                          ),
                        ],
                      ),
                    ),
                  );
                else
                  return const SizedBox();
              },
            );
          } else if (state is FaqsLoadingState) {
            return const Center(
              child: CircularProgressIndicator(),
            );
          }
          // else if (state is FaqsError) {
          //   String text = "";
          //   try {
          //     text = state.exception.toString().getErrorText();
          //   } catch (ex) {
          //     text = state.exception.toString();
          //   }
          //   return Center(
          //     child: Text(text),
          //   );
          // }
          else
            return const SizedBox();
        });
  }
}
