import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_markdown/flutter_markdown.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';

import '../../events/eventbus.dart';
import '../../events/events.dart';
import '../../generated/l10n.dart';
import '../../models/Subproduct.dart';
import '../../models/business.dart';
import '../../models/product.dart';
import '../../models/product_detail.dart';
import '../../store/actions.dart';
import '../../store/store.dart';
import '../../utils/http_util.dart';
import '../../utils/shop_scroll_controller.dart';
import '../../utils/shop_scroll_coordinator.dart';
import '../../utils/util_web.dart'
    if (dart.library.io) '../../utils/util_io.dart';
import '../../utils/utils.dart';
import '../../widgets/general/add_remove_button.dart';
import '../../widgets/general/carousel.dart';
import '../../widgets/general/show_price.dart';

MediaQueryData mediaQuery;
double statusBarHeight;
double screenHeight;
double screenWidth;

class MobileProductDetailPage extends StatefulWidget {
  final Business business;
  final Product product;

  const MobileProductDetailPage(
      {@required this.business, @required this.product, Key? key})
      : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return MobileProductDetailPageState();
  }
}

class MobileProductDetailPageState extends State<MobileProductDetailPage>
    with SingleTickerProviderStateMixin {
  ShopScrollCoordinator _shopCoordinator;
  ShopScrollController _pageScrollController;

  TabController _tabController;

  double _sliverAppBarInitHeight;
  double _sliverAppBarMaxHeight;
  final double _tabBarHeight = 50;

  ProductDetail productDetail;

  bool refresh;

  @override
  Widget build(BuildContext context) {
    store.dispatch(UpdateContext(context));

    if (productDetail == null) {
      return new Scaffold(
        body: Center(
          child: SpinKitWave(
            color: Colors.lightBlueAccent,
            size: 40.0,
          ),
        ),
      );
    }

    refresh = false;

    mediaQuery ??= MediaQuery.of(context);
    screenHeight ??= mediaQuery.size.height;
    screenWidth ??= mediaQuery.size.width;
    statusBarHeight ??= mediaQuery.padding.top;

    _sliverAppBarInitHeight ??= screenWidth;
    _sliverAppBarMaxHeight ??= screenWidth;

    _pageScrollController ??= _shopCoordinator
        .pageScrollController(_sliverAppBarMaxHeight - _sliverAppBarInitHeight);

    _shopCoordinator.pinnedHeaderSliverHeightBuilder ??= () {
      return statusBarHeight + kToolbarHeight + _tabBarHeight;
    };

    return Scaffold(
      body: Listener(
        onPointerUp: _shopCoordinator.onPointerUp,
        child: CustomScrollView(
          controller: _pageScrollController,
          physics: ClampingScrollPhysics(),
          slivers: <Widget>[
            SliverAppBar(
              pinned: true,
              floating: true,
              snap: true,
              leading: IconButton(
                icon: Icon(
                  Icons.arrow_back_ios,
                  color: Colors.black26,
                ),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              ),
              backgroundColor: Theme.of(context).primaryColor,
              expandedHeight: _sliverAppBarMaxHeight - 30.0,
              flexibleSpace: FlexibleSpaceBar(
                background: Carousel(
                  height: _sliverAppBarInitHeight + 0.0,
                  pages: _getProductPictures(context),
                  autoPlay: false,
                ),
              ),
            ),
            SliverPersistentHeader(
              pinned: false,
              floating: true,
              delegate: _SliverAppBarDelegate(
                minHeight: 60.0,
                maxHeight: 60.0,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Container(
                      padding:
                          EdgeInsets.only(left: 10.0, top: 5.0, right: 10.0),
                      child: Text(
                        productDetail.name,
                        style: TextStyle(
                            fontSize: 15.0, fontWeight: FontWeight.bold),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        ShowPrice(
                          productDetail.price,
                          currencySign: '\$',
                          fontWeight: FontWeight.bold,
                          smallFontSize: 14,
                          largeFontSize: 18,
                          regularPrice: productDetail.regularPrice,
                        ),
                        Container(
                          child: AddRemoveButton(
                            business: widget.business,
                            product: widget.product,
                          ),
                          padding: EdgeInsets.only(top: 5.0, right: 10.0),
                        ),
                      ],
                    )
                  ],
                ),
              ),
            ),
            SliverPersistentHeader(
              pinned: true,
              floating: false,
              delegate: _SliverAppBarDelegate(
                minHeight: _tabBarHeight,
                maxHeight: _tabBarHeight,
                child: Container(
                  color: Colors.white,
                  child: TabBar(
                    labelColor: new Color(0xFF3190E8),
                    unselectedLabelColor: new Color(0xFF666666),
                    indicatorColor: new Color(0xFF3190E8),
                    indicatorSize: TabBarIndicatorSize.label,
                    labelStyle: new TextStyle(
                      fontSize: 16.0,
                    ),
                    controller: _tabController,
                    tabs: <Widget>[
                      Tab(
                        text: S.of(context).detail,
                      ),
                      Tab(
                        text: S.of(context).specification,
                      ),
                    ],
                  ),
                ),
              ),
            ),
            SliverFillRemaining(
              child: TabBarView(
                controller: _tabController,
                children: <Widget>[
                  SingleChildScrollView(
                    controller: _shopCoordinator.newChildScrollController(),
                    child: Container(
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.start,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          (productDetail.subproducts.length > 0) ?
                          subProducts(productDetail.subproducts) :
                          SizedBox.shrink(),
                          Container(
                            padding: EdgeInsets.only(
                                top: 10.0, left: 10.0, right: 10.0),
                            child: Text(
                              productDetail.description,
                              style: TextStyle(
                                  fontSize: 14.0, color: Colors.black54),
                            ),
                          ),
                          Container(
                            padding: EdgeInsets.only(left: 10.0, right: 10.0),
                            child: (productDetail.description2 != null &&
                                    !productDetail.description2.isEmpty)
                                ? Text(
                                    '${productDetail.description2}',
                                    style: TextStyle(
                                        fontSize: 14.0, color: Colors.black54),
                                  )
                                : SizedBox.shrink(),
                          ),
                          productDetail.detailDescription != null
                              ? Container(
                                  padding:
                                      EdgeInsets.only(left: 10.0, right: 10.0),
                                  child: MarkdownBody(
                                    data: '${productDetail.detailDescription}',
                                    shrinkWrap: true,
                                  ),
                                )
                              : SizedBox.shrink(),
                        ],
                      ),
                    ),
                  ),
                  Container(
                    padding: EdgeInsets.only(
                        top: 10.0, left: 10.0, right: 10.0, bottom: 10.0),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Container(
                          child: Text(
                            S.of(context).weight_token(productDetail.weight),
                            style: TextStyle(
                              fontSize: 12.0,
                              color: Colors.black54,
                            ),
                          ),
                        ),
                        Container(
                          child: Text(
                            S.of(context).dimentions_token(
                                productDetail.dimentionsLength,
                                productDetail.dimentionsWidth,
                                productDetail.dimentionsHeight),
                            style: TextStyle(
                              fontSize: 12.0,
                              color: Colors.black54,
                            ),
                          ),
                        )
                      ],
                    ),
                  )
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

  @override
  void initState() {
    setState(() {
      refresh = false;
    });
    super.initState();
    _shopCoordinator = ShopScrollCoordinator();
    _tabController = TabController(vsync: this, length: 2);
    HttpUtil.httpGet(
      'v1/product-detail/${widget.product.id}',
      businessId: widget.business.id,
    ).then((value) {
      productDetail = ProductDetail.fromJson(value);
      setState(() {
        refresh = true;
      });
    }).catchError((error) {
      Utils.showMessageDialog(context, error, onOk: () {
        Navigator.of(context).pop();
        Navigator.of(context).pop();
      });
    });
    eventBus.on<OnCartInfoUpdated>().listen((event) {
      if (mounted) {
        setState(() {
          refresh = true;
        });
      }
    });
  }

  Widget subProducts(List<Subproduct> subproducts) {
    Column col = Column(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          padding: EdgeInsets.only(left: 6, top: 10, bottom: 10),
          child: Text(
            S.of(context).includes,
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
            ),
          ),
        )
      ],
    );
    for (int i = 0; i < subproducts.length; i++) {
      col.children.add(subProduct(subproducts[i]));
    }
    return col;
  }

  Widget subProduct(Subproduct subproduct) {
    Row row = Row(
      children: [],
    );
    row.children.add(
      Container(
        padding: EdgeInsets.symmetric(horizontal: 12.0, vertical: 5.0),
        child: Util.showImage(
          'https:${subproduct.product.image}',
          width: 48,
          height: 48,
          fit: BoxFit.contain,
        ),
      ),
    );
    row.children.add(
      Expanded(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                Expanded(
                  child: Container(
                    padding: EdgeInsets.only(left: 12, top: 5),
                    child: Text(
                      subproduct.product.name,
                      style: TextStyle(
                        fontSize: 15.0,
                      ),
                    ),
                  ),
                ),
                Container(
                  width: 80,
                  padding: EdgeInsets.only(left: 12, top: 5, right: 12),
                  child: Text(
                    '${subproduct.product.price.toStringAsFixed(2)}',
                    style: TextStyle(
                      fontSize: 13,
                      decoration: TextDecoration.lineThrough,
                    ),
                  ),
                  alignment: Alignment.centerRight,
                ),
                Container(
                  width: 60,
                  padding: EdgeInsets.only(left: 12, top: 5, right: 12),
                  child: Text(
                    'x${subproduct.quantity.toStringAsFixed(0)}',
                    style: TextStyle(
                      fontSize: 13,
                    ),
                  ),
                  alignment: Alignment.centerRight,
                ),
              ],
            ),
            Container(
              padding: EdgeInsets.only(left: 12, top: 12, right: 12),
              child: Text(
                '${subproduct.product.description}',
                style: TextStyle(
                  fontSize: 12,
                  color: Colors.black45,
                ),
              ),
            ),
          ],
        ),
      ),
    );
    return Container(
      padding: EdgeInsets.only(left: 0, right: 0, top: 0, bottom: 0),
      child: row,
    );
  }

  List<Widget> _getProductPictures(BuildContext context) {
    var pages = <Widget>[];
    List<String> images = [];
    images.add(productDetail.image);
    for (var i = 0; i < productDetail.images.length; i++) {
      // print('>>https:' + productDetail.images[i].image);
      images.add(productDetail.images[i].image);
    }

    for (var i = 0; i < images.length; i++) {
      pages.add(new GestureDetector(
        child: new Container(
          child: Util.showImage(
            'https:' + images[i],
          ),
        ),
        onTap: () {},
      ));
    }
    return pages;
  }

  @override
  void dispose() {
    _tabController?.dispose();
    _pageScrollController?.dispose();
    super.dispose();
  }
}

class _SliverAppBarDelegate extends SliverPersistentHeaderDelegate {
  _SliverAppBarDelegate({
    @required this.minHeight,
    @required this.maxHeight,
    @required this.child,
  });

  final double minHeight;
  final double maxHeight;
  final Widget child;

  @override
  double get minExtent => this.minHeight;

  @override
  double get maxExtent => max(maxHeight, minHeight);

  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    return SizedBox.expand(child: child);
  }

  @override
  bool shouldRebuild(_SliverAppBarDelegate oldDelegate) {
    return maxHeight != oldDelegate.maxHeight ||
        minHeight != oldDelegate.minHeight ||
        child != oldDelegate.child;
  }
}
