import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_markdown/flutter_markdown.dart';
import 'package:markdown_widget/config/style_config.dart';
import 'package:modal_progress_hud_nsn/modal_progress_hud_nsn.dart';
import 'package:road24_mobile/model/blocs/notifications/notifications_bloc.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/video_items.dart';
import 'package:road24_mobile/view/built/i18n.dart';
import 'package:road24_mobile/view/home/dash_board.dart';
import 'package:road24_mobile/view/mycar/add/inspection/widgets/custom_bottom_sheet.dart';
import 'package:url_launcher/url_launcher.dart';

import 'package:video_player/video_player.dart' as videoPlayer;
import 'package:markdown_widget/markdown_widget.dart' as markd;

class NotificationDetails extends StatefulWidget {
  final String title;
  final int id;
  const NotificationDetails({Key? key, required this.title, required this.id})
      : super(key: key);

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

class NotificationDetailsState extends State<NotificationDetails> {
  @override
  void initState() {
    super.initState();
    DashBoard.notificationsBloc.add(GetNotificationDetailsEvent(id: widget.id));
  }

  @override
  Widget build(BuildContext context) {
    return BlocBuilder(
      bloc: DashBoard.notificationsBloc,
      builder: (context, state) {
        return ModalProgressHUD(
          inAsyncCall: state is NotificationsInitial,
          child: Scaffold(
              bottomSheet: CustomBottomSheet(
                onTap: () async {
                  Navigator.pop(context);
                },
                buttonColor: Colors.black,
                title: '${S.of(context).back}',
              ),
              appBar: AppBar(
                  leading: FrequentWidgets.appBarBackButton(context),
                  title: Text(widget.title,
                      style: AppStyle.textStyle().copyWith(
                          color: Colors.black,
                          fontSize: 17.0,
                          fontWeight: FontWeight.w600))),
              backgroundColor: AppColors.appPrimaryColor,
              body: state is GetNotificationsDetailsSuccessState
                  ? Container(
                      margin: EdgeInsets.only(left: 16, right: 16, bottom: 100),
                      decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(16)),
                      // child: flutterMarkdown()),
                      child: markdownWidget(context, state.markdownStr))
                  : SizedBox()),
        );
      },
    );
  }

  markdownWidget(context, String data) {
    return markd.MarkdownWidget(
      childMargin: EdgeInsets.all(12),
      data: data,
      // controller: controller,

      styleConfig: StyleConfig(
          pConfig: PConfig(
            onLinkTap: (url) {
              if (url != null) _launchURL(url);
            },
          ),
          imgBuilder: (String url, attributes) {
            return Image.network(url);
          },
          videoBuilder: (String? url, attributes) {
            if (url != null) {
              // if (url.contains("youtu")) {
              //   print("youtube.....");
              //   var id = YoutubePlayer.convertUrlToId("$url");

              //   var _controller = YoutubePlayerController(
              //     initialVideoId: id!,
              //     flags: YoutubePlayerFlags(
              //       mute: false,
              //       autoPlay: false,
              //       controlsVisibleAtStart: true,
              //     ),
              //   );

              //   return YoutubePlayer(
              //     controller: _controller,
              //   );
              // } else
              return VideoItems(
                videoPlayerController:
                    videoPlayer.VideoPlayerController.network(
                  url,
                ),
                looping: false,
                autoplay: false,
              );
            }
            return Container();
          },
          videoConfig: VideoConfig(autoInitialize: true)),
    );
  }

  _launchURL(String url) async {
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      throw 'Could not launch $url';
    }
  }

  flutterMarkdown() {
    return Markdown(
      shrinkWrap: true,
      data: md2,
      styleSheetTheme: MarkdownStyleSheetBaseTheme.cupertino,
      onTapLink: (text, url, title) {
        print("text....$text");
        print("url....$url");
        print("title....$title");
        if (url != null) launch(url);
      },
      styleSheet: MarkdownStyleSheet(
          // textAlign: WrapAlignment.center,
          h1: AppStyle.textStyle().copyWith(
              color: Color(0xff282828),
              fontSize: 24.0,
              fontWeight: FontWeight.w700),
          h2: AppStyle.textStyle().copyWith(
              color: Color(0xff282828),
              fontSize: 20.0,
              fontWeight: FontWeight.w600),
          a: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.w500,
              color: Colors.blue,
              decoration: TextDecoration.underline),
          p: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.w500,
              color: Color(0xff282828))),
    );
  }

  final String md2 = '''
  
   \n# I'm h1\n## I'm h2\n### I'm h3\n#### I'm h4\n###### I'm h5\n###### I'm h6\n\n```\nclass MarkdownHelper {\n  Map<String, Widget> getTitleWidget(m.Node node) => title.getTitleWidget(node);\n Widget getPWidget(m.Element node) => p.getPWidget(node);\nWidget getPreWidget(m.Node node) => pre.getPreWidget(node);\n}\n```\n\n\n*italic text*\n\n**strong text**\n\n`I'm code`\n\n~~del~~\n\n***~~italic strong and del~~***\n\n> Test for blockquote and **strong**\n\n- ul list\n- one\n    - aa *a* a\n    - bbbb\n        - CCCC\n\n1. ol list\n2. aaaa\n3. bbbb\n    1. AAAA\n    2. BBBB\n    3. CCCC\n\n\n[I'm link](https://github.com/asjqkkkk/flutter-todos)\n\n\n[ ] I'm *CheckBox*\n\n[x] I'm *CheckBox* too\n\nTest for divider(hr):\n\n---\n\nTest for Table:\n\nheader 1 | header 2\n---|---\nrow 1 col 1 | row 1 col 2\nrow 2 col 1 | row 2 col 2\n\nGif:\n\n![](http://i.imgur.com/Ssfp7.gif)\n\nHtml Image:\n\n\n<img src="assets/brand/placeholder.jpeg"/>\n\nVideo:\n\n<video src="https://cdn.yhxbb.uz/mvd/835a3769ae3b4d1588b9260477670219.mp4?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=qy6w9DjbV4K6%2FxRs3XhM%2F20211108%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20211108T174602Z&X-Amz-Expires=604800&X-Amz-SignedHeaders=host&X-Amz-Signature=0d9cbde610694f1f43af2602daea9903ac05e9ca697dc290095a48543ceee4e8">\n\nYoutube video:\n\n<video src="https://youtu.be/GVTRJa4B4fY">\n\n
''';

  final String md = '''
# ТИК ЧИЗИҚЛАР

**Тик чизиқлар** — йўл иншоотлари ва жиҳозлари юзаларига кетма-кет чизилган йўл-йўл оқ-қора чизиқлар мажмуасидан иборат бўлиб, уларнинг ўлчамларини кўрсатишда, кўз билан чамалаш воситаси сифатида хизмат қилади.

![](https://upload.wikimedia.org/wikipedia/commons/2/22/1_Nature_1.png)


ҳаракатланаётган транспорт воситаларига хавф туғдирадиган йўл иншоотларининг тик элементлари (кўприклар, йўл ўтказгич ва эстакадалар, устунлар ва ҳ. к.)ни билдиради;

## «2.2»

[Markdown Live Preview](https://markdownlivepreview.com/)
_туннеллар, кўприклар, йўл ўтказгич ва эстакадаларнинг_ пастки пештоқини билдиради;

## «2.3»

![](http://i.imgur.com/Ssfp7.gif)

**ажратиш бўлакларидаги** ёки хавфсизлик оролчаларидаги думалоқ устунларни билдиради;


<video src="https://www.learningcontainer.com/wp-content/uploads/2020/05/sample-mp4-file.mp4">

<img src="https://i.imgur.com/vKb2F1B.png"/>



## «2.4»

йўналтирувчи, бетон ёки темир бетон устунлар, тўсиқ тиргаклар ва ҳоказоларни билдиради;



## «2.5»

йўлнинг кичик радиусли бурилиш, тик нишаблик ва бошқа хавфли жойларда йўл тўсиқларининг ён юзаларини билдиради;


## «2.6»

бошқа жойлардаги тўсиқларнинг ён юзаларини билдиради;


## «2.7»

хавфли жойлардаги тўсиқни (бордюрни) ва йўл сатҳидан баланд бўлган хавфсизлик оролчаларини билдиради.

''';
}
