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

import '../../constants.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/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/bottom_nav.dart';
import '../../widgets/general/breadcrumbs.dart';
import '../../widgets/general/carousel.dart';
import '../../widgets/general/navigationbar.dart';
import '../../widgets/general/show_price.dart';
import 'desktop_shopping_cart_widget.dart';

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

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

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

class DesktopProductDetailPageState extends State<DesktopProductDetailPage>
    with SingleTickerProviderStateMixin {

  TabController _tabController;

  final double _tabBarHeight = 50;

  ProductDetail productDetail;

  bool refresh;

  double sideSpace = 0;
  double mainSpace = 1200;

  @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;

    if (MediaQuery.of(context).size.width <= 1200) {
      mainSpace = MediaQuery.of(context).size.width;
      sideSpace = 0;
    } else {
      mainSpace = 1200;
      sideSpace = (MediaQuery.of(context).size.width - 1200) / 2;
    }

    return Scaffold(
      appBar: MiniNavigationBar(
        title: S.of(context).shop,
        back: true,
        breadCrumbs: [
          BreadCrumb(productDetail.name, null),
        ],
        breadCrumbHeight: Constants.BREADCRUMB_HEIGHT,
        // shoppingCart: DesktopShoppingCartWidget(business: widget.business,),
      ),
      body: SingleChildScrollView(
        child: Container(
          child: Row(
            children: [
              Container(
                width: sideSpace,
              ),
              Expanded(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    Container(
                      margin: EdgeInsets.only(top: 30.0, left: 16.0, right: 16.0, bottom: 30.0),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Expanded(
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.start,
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                getImage(mainSpace * 0.50),
                                Container(
                                  margin: EdgeInsets.only(top: 10),
                                  child: Text(
                                    'SKU: ${productDetail.sku}',
                                    overflow: TextOverflow.ellipsis,
                                    maxLines: 2,
                                    style: TextStyle(
                                      color: Colors.black45,
                                      fontSize: 12.0,
                                    ),
                                  ),
                                ),
                                Container(
                                  child: Text(
                                    productDetail.name,
                                    overflow: TextOverflow.ellipsis,
                                    maxLines: 2,
                                    style: TextStyle(
                                      fontWeight: FontWeight.bold,
                                      fontSize: 20.0,
                                    ),
                                  ),
                                ),
                                Container(
                                  padding: EdgeInsets.only(top: 10, bottom: 20),
                                  child: Text(
                                    '${productDetail.description}',
                                    overflow: TextOverflow.ellipsis,
                                    maxLines: 3,
                                    style: TextStyle(
                                      color: Colors.black54,
                                      fontSize: 15,
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                          Container(
                            width: mainSpace * 0.5,
                            padding: EdgeInsets.only(top: 16.0, left: 16.0, right: 16.0, bottom: 16.0),
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.start,
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Container(
                                  margin: EdgeInsets.only(bottom: 16.0),
                                  child: Row(
                                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      ShowPrice(
                                        productDetail.price,
                                        currencySign: '\$',
                                        fontWeight: FontWeight.bold,
                                        smallFontSize: 24,
                                        largeFontSize: 40,
                                        regularPrice: productDetail.regularPrice,
                                      ),
                                      AddRemoveButton(
                                        product: widget.product,
                                        business: widget.business,
                                        addToBasket: true,
                                      ),
                                    ],
                                  ),
                                ),
                                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,
                                    ),
                                  ],
                                ),
                                Container(
                                  height: mainSpace / 2,
                                  child: TabBarView(
                                    controller: _tabController,
                                    children: <Widget>[
                                      SingleChildScrollView(
                                        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, bottom: 16.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,
                                                ),
                                              ),
                                            )
                                          ],
                                        ),
                                      )
                                    ],
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
              Container(
                width: sideSpace,
              ),
            ],
          ),
        ),
      ),
      bottomNavigationBar: BottomNav(),
    );
  }

  Widget getImage(double width) {
    if (productDetail.images.length <= 0) {
      return Util.showImage(
        productDetail.image,
        width: width,
        height: width,
      );
    } else {
      return Carousel(
        height: width,
        pages: _getProductPictures(context),
        autoPlay: true,
        duration: Duration(seconds: 10,),
      );
    }
  }

  Widget subProducts(List<Subproduct> subproducts) {
    Column col = Column(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          padding: EdgeInsets.only(left: 12, 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,
    );
  }

  @override
  void initState() {
    setState(() {
      refresh = false;
    });
    super.initState();
    _tabController = TabController(vsync: this, length: 2);
    HttpUtil.httpGet(
      'v1/product-detail/${widget.product.id}',
      businessId: widget.business.id,
    ).then((value) {
      print(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;
        });
      }
    });
  }

  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();
    super.dispose();
  }
}
