import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:peasmartcare/blocs/additional_service_detail/additional_service_detail_bloc.dart';
import 'package:peasmartcare/blocs/additional_service_history/additional_service_history_bloc.dart';
import 'package:peasmartcare/components/body_layout.dart';
import 'package:peasmartcare/components/header_content.dart';
import 'package:peasmartcare/components/pea_app_bar.dart';
import 'package:peasmartcare/components/profile_avatar.dart';
import 'package:peasmartcare/constraints/api_path.dart';
import 'package:peasmartcare/constraints/app_data.dart';
import 'package:peasmartcare/constraints/image_asset.dart';
import 'package:peasmartcare/models/additional_service_model.dart';
import 'package:peasmartcare/pages/auth/logout.dart';
import 'package:peasmartcare/utils/share_data_util.dart';
import 'package:peasmartcare/widgets/empty_box.dart';
import 'package:peasmartcare/widgets/loading.dart';
import 'package:peasmartcare/widgets/sweetalert/sweetalert.dart';
import 'package:webview_flutter_plus/webview_flutter_plus.dart';

class AdditionalServiceDetail extends StatefulWidget {
  @override
  _AdditionalServiceDetailState createState() => _AdditionalServiceDetailState();
}

class _AdditionalServiceDetailState extends State<AdditionalServiceDetail> {
  WebViewPlusController _webViewController;
  String urlPath;
  double _webViewHeight = 400;

  @override
  void initState() {
    context.read<AdditionalServiceDetailBloc>().add(AdditionalServiceDetailGetData());

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: PEAAppBar(
        title: "บริการเสริม",
        actions: <Widget>[
          ProfileAvatar(),
        ],
      ),
      // bottomNavigationBar: PEABottomBar(),
      body: BlocListener<AdditionalServiceDetailBloc, AdditionalServiceDetailState>(
        listener: (context, state) {
          if (state is AdditionalServiceDetailErrorUnauthorized) {
            Navigator.of(context).popUntil((route) => route.isFirst);
            Navigator.pushReplacement(
              context,
              MaterialPageRoute(builder: (context) => LogoutPage()),
            );
          }
        },
        child: BodyLayout(
          top: 0,
          layoutType: LayoutType.ONLY_CHILD,
          child: Column(
            children: <Widget>[
              Stack(
                children: <Widget>[
                  BlocBuilder<AdditionalServiceDetailBloc, AdditionalServiceDetailState>(
                    builder: (context, state) {
                      if (state is AdditionalServiceDetailLoading) {
                        return Loading();
                      } else if (state is AdditionalServiceDetailLoaded) {
                        AdditionalServiceModel item = state.result;

                        return HeaderContent(
                          title: item.subject,
                          icon: ImageAsset.additionalServiceImg,
                          height: 180,
                        );
                      }

                      return EmptyBox();
                    },
                  ),
                  BlocListener<AdditionalServiceDetailBloc, AdditionalServiceDetailState>(
                    listener: (context, state) {
                      if (state is AdditionalServiceDetailLoaded) {
                        if (state.saveSuccess != null && state.saveSuccess) {
                          SweetAlert.show(
                            context,
                            subtitle: "ทาง PEA ได้รับคำขอใช้บริการเสริมของท่านแล้ว หลังจากนี้จะมีพนักงานดูแลลูกค้าติดต่อท่านเพื่อสอบถามรายละเอียดเพิ่มเติม",
                            style: SweetAlertStyle.success,
                            showCancelButton: false,
                            onPress: (bool isConfirm) {
                              context.read<AdditionalServiceHistoryBloc>().add(AdditionalServiceHistoryGetList());
                              Navigator.pop(context);
                              Navigator.pop(context);

                              return false;
                            },
                          );
                        } else if (state.saveSuccess != null && !state.saveSuccess) {
                          SweetAlert.show(
                            context,
                            subtitle: "ขอใช้บริการไม่สำเร็จ",
                            style: SweetAlertStyle.error,
                          );
                        }
                      } else if (state is AdditionalServiceDetailErrorUnauthorized) {
                        Navigator.of(context).popUntil((route) => route.isFirst);
                        Navigator.pushReplacement(
                          context,
                          MaterialPageRoute(builder: (context) => LogoutPage()),
                        );
                      }
                    },
                    child: BlocBuilder<AdditionalServiceDetailBloc, AdditionalServiceDetailState>(
                      builder: (context, state) {
                        if (state is AdditionalServiceDetailLoading) {
                          return Loading();
                        } else if (state is AdditionalServiceDetailLoaded) {
                          AdditionalServiceModel item = state.result;

                          return _body(item);
                        }

                        return EmptyBox();
                      },
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _body(AdditionalServiceModel data) {
    return Positioned(
      child: Padding(
        padding: const EdgeInsets.only(top: 90),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[_buildDetail(data)],
        ),
      ),
    );
  }

  Widget _buildDetail(AdditionalServiceModel data) {
    Size deviceSize = MediaQuery.of(context).size;

    return Card(
      elevation: 3,
      child: Container(
        width: deviceSize.width - 40,
        height: _webViewHeight + 100,
        padding: EdgeInsets.all(15),
        child: Column(
          children: <Widget>[
            Container(
              // width: deviceSize.width - 40,
              height: _webViewHeight,
              padding: EdgeInsets.all(15),
              child: WebViewPlus(
                javascriptMode: JavascriptMode.unrestricted,
                onWebViewCreated: (controller) {
                  this._webViewController = controller;

                  urlPath = '${APIPath.additionalServiceWebView}?id=${data.id}&authenKey=${ShareDataUtil.getAuthenKey()}';

                  print(urlPath);

                  controller.loadUrl(Uri.encodeFull(urlPath));
                  // controller.loadString(
                  //   utf8.decode(base64.decode(data.detailBase64)),
                  //   mimeType: 'text/html',
                  //   encoding: Encoding.getByName('utf-8'),
                  // );
                },
                onPageFinished: (url) {
                  _webViewController.getHeight().then((double height) {
                    setState(() {
                      _webViewHeight = height;
                    });
                  });

                  // print("===== url ========");
                  // print(url);

                  // print(url.contains('data:text/html;base64,'));
                  // if (url.contains('data:text/html;base64,')) {
                  //   Navigator.pop(context);
                  //   print("poppppp");
                  // }
                },
              ),
            ),
            Padding(
              padding: const EdgeInsets.only(top: 20),
              child: RaisedButton(
                color: Color(AppData.yellowColor),
                child: const Text('ขอใช้บริการเสริม', style: TextStyle(fontSize: 20, color: Color(AppData.whiteColor))),
                onPressed: () {
                  context.read<AdditionalServiceDetailBloc>().add(
                        AdditionalServiceDetailOnSave(id: data.id),
                      );
                },
              ),
            )
          ],
        ),
      ),
    );
  }
}
