import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:peasmartcare/blocs/news_detail/news_detail_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/news_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/error_box.dart';
import 'package:peasmartcare/widgets/loading.dart';
import 'package:peasmartcare/widgets/not_found_box.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:webview_flutter_plus/webview_flutter_plus.dart';

class NewsDetail extends StatefulWidget {
  final String id;

  const NewsDetail({Key key, this.id}) : super(key: key);
  @override
  _NewsDetailState createState() => _NewsDetailState();
}

class _NewsDetailState extends State<NewsDetail> {
  WebViewPlusController _webViewController;
  double _webViewHeight = 400;
  String urlPath;

  @override
  void initState() {
    urlPath = '${APIPath.newsDetailWebView}?id=${widget.id}&AuthenKey=${ShareDataUtil.getAuthenKey()}';
    context.read<NewsDetailBloc>().add(
          NewsDetailGetData(id: widget.id),
        );

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: PEAAppBar(
        title: "ข่าวประชาสัมพันธ์",
        actions: <Widget>[
          ProfileAvatar(),
        ],
      ),
      // bottomNavigationBar: PEABottomBar(),
      body: BlocListener<NewsDetailBloc, NewsDetailState>(
        listener: (context, state) {
          if (state is NewsDetailErrorUnauthorized) {
            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<NewsDetailBloc, NewsDetailState>(
                    builder: (context, state) {
                      if (state is NewsDetailLoading) {
                        return Loading();
                      } else if (state is NewsDetailLoaded) {
                        NewsModel item = state.result;

                        return HeaderContent(
                          title: Column(
                            mainAxisAlignment: MainAxisAlignment.start,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                item.subject,
                                overflow: TextOverflow.ellipsis,
                                style: TextStyle(
                                  color: Color(AppData.yellowColor),
                                  fontWeight: FontWeight.bold,
                                  fontSize: 24,
                                ),
                                maxLines: 1,
                              ),
                              Text(
                                item.typeName,
                                overflow: TextOverflow.ellipsis,
                                style: TextStyle(
                                  color: Color(AppData.yellowColor),
                                  fontWeight: FontWeight.bold,
                                  fontSize: 18,
                                ),
                                maxLines: 1,
                              ),
                              Text(
                                item.dateTime,
                                overflow: TextOverflow.ellipsis,
                                style: TextStyle(
                                  color: Color(AppData.yellowColor),
                                  fontWeight: FontWeight.bold,
                                  fontSize: 16,
                                ),
                              ),
                            ],
                          ),
                          icon: ImageAsset.newsImg,
                          height: 180,
                        );
                      }

                      return EmptyBox();
                    },
                  ),
                  BlocListener<NewsDetailBloc, NewsDetailState>(
                    listener: (context, state) {
                      if (state is NewsDetailErrorUnauthorized) {
                        Navigator.of(context).popUntil((route) => route.isFirst);
                        Navigator.pushReplacement(
                          context,
                          MaterialPageRoute(builder: (context) => LogoutPage()),
                        );
                      }
                    },
                    child: BlocBuilder<NewsDetailBloc, NewsDetailState>(
                      builder: (context, state) {
                        if (state is NewsDetailLoading) {
                          return Loading();
                        } else if (state is NewsDetailLoaded) {
                          NewsModel item = state.result;
                          return _body(item);
                        } else if (state is NewsDetailNotFound) {
                          return NotFoundBox();
                        } else if (state is NewsDetailError) {
                          return ErrorBox(
                            message: state.message,
                          );
                        }

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

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

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

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

            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 + 100;
              });
            });
          },
        ),
      ),
    );
  }
}
