import 'dart:async';
import 'dart:convert';

import 'package:firebase_analytics/firebase_analytics.dart';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:video_player/video_player.dart';

import '../../../core/i18n/translations.g.dart';
import '../../../core/styles/my_colors.dart';
import '../../../core/styles/my_dimensions.dart';
import '../../../core/styles/my_font.dart';
import '../../../data/models/userex/userexdetailmodel.dart';
import '../../widgets/ipm_image.dart';
import 'package:http/http.dart' as http;

import '../../widgets/ipm_title_text.dart';

class UserExperienceScreen extends StatefulWidget {
  final String id;

  UserExperienceScreen({
    Key? key,
    required this.id,
  }) : super(key: key);

  @override
  State<UserExperienceScreen> createState() => _UserExperienceScreenState();
}

class _UserExperienceScreenState extends State<UserExperienceScreen> {
  late VideoPlayerController _controller;
  late Future<void> _initializeVideoPlayerFuture;
  late Timer _timer;
  late String lang = '';
  late String urL = '';
  final GlobalKey webViewKey = GlobalKey();

  int _start = 1;
  bool loading = true;
  UserExDetailModel? userExDetailModel;
  InAppWebViewController? webViewController;
  InAppWebViewGroupOptions options = InAppWebViewGroupOptions(
      crossPlatform: InAppWebViewOptions(
        useShouldOverrideUrlLoading: true,
        mediaPlaybackRequiresUserGesture: false,
      ),
      android: AndroidInAppWebViewOptions(
        useHybridComposition: true,
      ),
      ios: IOSInAppWebViewOptions(
        allowsInlineMediaPlayback: true,
      ));

  late PullToRefreshController pullToRefreshController;
  String url = "";
  double progress = 0;
  final urlController = TextEditingController();

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

    // Create and store the VideoPlayerController. The VideoPlayerController
    // offers several different constructors to play videos from assets, files,
    // or the internet.
    _controller = VideoPlayerController.network(
      'https://ipmart.ipthailand.go.th/uploads/Content/dip-videos/1%20%E0%B8%AA%E0%B8%B4%E0%B8%97%E0%B8%98%E0%B8%B4%E0%B8%9A%E0%B8%B1%E0%B8%95%E0%B8%A3.mp4',
    );

    _initializeVideoPlayerFuture = _controller.initialize();

    // _controller.addListener(() {
    //   setState(() {});
    // });
    startTimer();
    getLang();
    _controller.setLooping(true);
    _controller.initialize();
    _controller.play();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  void startTimer() {
    const oneSec = const Duration(seconds: 1);
    _timer = new Timer.periodic(
      oneSec,
      (Timer timer) => setState(
        () {
          if (_start < 1) {
            setState(() {
              loading = false;
            });
            timer.cancel();
          } else {
            _start = _start - 1;
          }
        },
      ),
    );
  }

  getLang() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();

    setState(() {
      lang = prefs.getString('lang').toString();
    });
    await FirebaseAnalytics.instance.logScreenView(screenName: 'UserEx');
    await getUserEx(widget.id);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: loading == true
          ? Center(
              child: CircularProgressIndicator(
                color: Colors.redAccent,
              ),
            )
          : SingleChildScrollView(
              child: Container(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        GestureDetector(
                          child: Container(
                            child: Icon(Icons.arrow_back_ios_new),
                            width: MyDimens.dimen40,
                            height: MyDimens.dimen40,
                            margin: EdgeInsets.only(
                              top: MyDimens.dimen80,
                              left: MyDimens.dimen16,
                            ),
                          ),
                          onTap: () {
                            Navigator.pop(context);
                          },
                        ),
                        Container(
                          child: lang == "th" || lang == null
                              ? IPMTitleText(
                                  title1:
                                      AppLocalizations.home.user_ex_th_title1,
                                  title2:
                                      AppLocalizations.home.user_ex_th_title2,
                                )
                              : IPMTitleText(
                                  title1:
                                      AppLocalizations.home.user_ex_en_title1,
                                  title2:
                                      AppLocalizations.home.user_ex_en_title2,
                                ),
                          alignment: Alignment.centerLeft,
                          margin: EdgeInsets.only(
                            left: MyDimens.dimen16,
                            top: MyDimens.dimen80,
                          ),
                        ),
                      ],
                    ),
                    Container(
                      alignment: Alignment.topLeft,
                      margin: EdgeInsets.only(
                        left: MyDimens.dimen24,
                        right: MyDimens.dimen24,
                        top: MyDimens.dimen24,
                        bottom: MyDimens.dimen8,
                      ),
                      width: MyDimens.dimen160,
                      child: Text(
                        userExDetailModel!.result!.postTitle ?? '',
                        textAlign: TextAlign.start,
                        style: MyFont.bold20.copyWith(
                          color: MyColor.headerColor,
                          overflow: TextOverflow.ellipsis,
                        ),
                        maxLines: 2,
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.only(
                          left: MyDimens.dimen24,
                          right: MyDimens.dimen24,
                          top: 0,
                          bottom: 0),
                      // width: MyDimens.dimen160,
                      child: Text(
                        userExDetailModel!.result!.postName ?? "",
                        style: MyFont.regular14.copyWith(
                          color: MyColor.grey,
                          overflow: TextOverflow.ellipsis,
                        ),
                        maxLines: 500,
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.only(
                        left: 0,
                        right: 0,
                        top: MyDimens.dimen16,
                        bottom: MyDimens.dimen16,
                      ),
                      width: MediaQuery.of(context).size.width,
                      height: MyDimens.dimen245,
                      // alignment: Alignment.topCenter,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(0),
                      ),
                      child: ClipRRect(
                        borderRadius: BorderRadius.circular(0),
                        child: IPMImage(
                          url: userExDetailModel!.result!.cover ?? '',
                          fit: BoxFit.fill,
                        ),
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.only(
                          left: MyDimens.dimen24,
                          right: MyDimens.dimen24,
                          top: 0,
                          bottom: MyDimens.dimen16),
                      // width: MyDimens.dimen160,
                      child: Text(
                        userExDetailModel!.result!.postExcerpt ?? '',
                        style: MyFont.regular14.copyWith(
                          color: MyColor.headerColor,
                          overflow: TextOverflow.ellipsis,
                        ),
                        maxLines: 100,
                      ),
                    ),
                    Container(
                      alignment: Alignment.topLeft,
                      margin: EdgeInsets.only(
                          left: MyDimens.dimen24,
                          right: MyDimens.dimen8,
                          top: 0,
                          bottom: MyDimens.dimen24),
                      width: MyDimens.dimen160,
                      child: Text(
                        AppLocalizations.products.detail_title_1 ?? '',
                        textAlign: TextAlign.start,
                        style: MyFont.bold20.copyWith(
                          color: MyColor.headerColor,
                          overflow: TextOverflow.ellipsis,
                        ),
                        maxLines: 2,
                      ),
                    ),
                    Container(
                      child: InAppWebView(
                        key: webViewKey,
                        initialUrlRequest:
                            URLRequest(url: Uri.parse('${urL}.mp4')),
                        initialOptions: options,
                        onWebViewCreated: (controller) {
                          webViewController = controller;
                        },
                        onLoadStart: (controller, url) {
                          setState(() {});
                        },
                        androidOnPermissionRequest:
                            (controller, origin, resources) async {
                          return PermissionRequestResponse(
                              resources: resources,
                              action: PermissionRequestResponseAction.GRANT);
                        },
                        shouldOverrideUrlLoading:
                            (controller, navigationAction) async {
                          var uri = navigationAction.request.url!;

                          if (![
                            "http",
                            "https",
                            "file",
                            "chrome",
                            "data",
                            "javascript",
                            "about"
                          ].contains(uri.scheme)) {
                            if (await canLaunch(url)) {
                              // Launch the App
                              await launch(
                                url,
                              );
                              // and cancel the request
                              return NavigationActionPolicy.CANCEL;
                            }
                          }

                          return NavigationActionPolicy.ALLOW;
                        },
                        onLoadStop: (controller, url) async {
                          // pullToRefreshController.endRefreshing();
                          // setState(() {
                          //   this.url = url.toString();
                          //   urlController.text = this.url;
                          // });
                        },
                        onLoadError: (controller, url, code, message) {
                          // pullToRefreshController.endRefreshing();
                        },
                        onProgressChanged: (controller, progress) {
                          if (progress == 100) {
                            // pullToRefreshController.endRefreshing();
                          }
                          setState(() {
                            // this.progress = progress / 100;
                            // urlController.text = this.url;
                          });
                        },
                        // onUpdateVisitedHistory: (controller, url, androidIsReload) {
                        //   setState(() {
                        //     this.url = url.toString();
                        //     urlController.text = this.url;
                        //   });
                        // },
                        onConsoleMessage: (controller, consoleMessage) {
                          print(consoleMessage);
                        },
                      ),
                      height: MyDimens.dimen245,
                    ),
                    SizedBox(
                      height: MyDimens.dimen40,
                    ),
                    Row(
                      children: [
                        Spacer(),
                        Container(
                          margin: EdgeInsets.only(
                              left: MyDimens.dimen24,
                              right: MyDimens.dimen24,
                              top: 0,
                              bottom: 16),
                          alignment: Alignment.topLeft,
                          width: MyDimens.dimen52,
                          height: MyDimens.dimen52,
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(8),
                          ),
                          child: ClipRRect(
                            borderRadius: BorderRadius.circular(8),
                            child: IPMImage(
                              url: userExDetailModel!.result!.image ?? '',
                              fit: BoxFit.cover,
                            ),
                          ),
                        ),
                        Column(
                          children: [
                            Container(
                              margin: EdgeInsets.only(
                                  left: 0,
                                  right: MyDimens.dimen8,
                                  top: 0,
                                  bottom: 2),
                              width: MyDimens.dimen168,
                              child: Text(
                                userExDetailModel!.result!.attributeName ?? '',
                                style: MyFont.regular14.copyWith(
                                  color: Colors.black,
                                  overflow: TextOverflow.ellipsis,
                                ),
                                maxLines: 2,
                              ),
                            ),
                            Container(
                              margin: EdgeInsets.only(
                                  left: 0,
                                  right: MyDimens.dimen8,
                                  top: 0,
                                  bottom: 0),
                              width: MyDimens.dimen168,
                              child: Text(
                                userExDetailModel!.result!.attributePosition ??
                                    '',
                                style: MyFont.regular14.copyWith(
                                  color: MyColor.grey,
                                  overflow: TextOverflow.ellipsis,
                                ),
                                maxLines: 2,
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                    SizedBox(
                      height: MyDimens.dimen40,
                    ),
                  ],
                ),
              ),
            ),
    );
  }

  getUserEx(String id) async {
    var _model;
    var _fail;
    var result;
    String url = "https://ipmart.ipthailand.go.th/api/user-exp/${id}";
    // Object body = {
    //   "id": "${id}",
    // };
    // print(body);
    var response = await http.get(
      Uri.parse(url),
    );
    // print(url);
    // print("encrytion body=> ${body}");
    var res = json.decode(response.body);
    print("response.body => ${res}");
    print("response.body encrytion=> ${response.body}");
    print("================================");
    // if (response.statusCode == 200) {
    _model = UserExDetailModel.fromJson(
        json.decode(utf8.decode(response.bodyBytes)));
    userExDetailModel = _model;

    final values =
        userExDetailModel!.result!.postContent.toString().split('url=\"');
    // String aaa = values[1].toString();
    // aaa.split('/');
    final newString1 = values[1].toString().replaceAll('>', "");
    final newString2 = newString1.toString().replaceAll('"', "");
    if (userExDetailModel!.result!.id == 19) {
    } else {}
    final asss = newString2.split('.mp4');
    urL = asss[0];

    print("URL=> ${userExDetailModel!.result!.postContent}");
    print("URL=> ${urL}");
    print("URL=> ${Uri.parse('${urL}4')}");
  }
}
