import 'package:cached_network_image/cached_network_image.dart';

import 'package:e_commerce_training/res/R.dart';
import 'package:e_commerce_training/src/model/repository/app_repository.dart';
import 'package:e_commerce_training/src/model/response/product_detail_response.dart';
import 'package:e_commerce_training/src/page/shopping_cart/shopping_cart_cubit.dart';
import 'package:e_commerce_training/src/page/shopping_cart/shopping_cart_state.dart';
import 'package:e_commerce_training/src/util/util.dart';
import 'package:e_commerce_training/src/widget/custom_appbar.dart';
import 'package:e_commerce_training/src/widget/pending_action.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:material_design_icons_flutter/material_design_icons_flutter.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:easy_localization/easy_localization.dart';

class ShoppingCartPage extends StatefulWidget {
  @override
  _ShoppingCartPageState createState() => _ShoppingCartPageState();
}

class _ShoppingCartPageState extends State<ShoppingCartPage> {
  late ShoppingCartCubit _cubit;
  RefreshController _refreshController = RefreshController(initialRefresh: false);

  @override
  void initState() {
    // TODO: implement initState
    AppRepository repository = AppRepository();
    _cubit = ShoppingCartCubit(repository);
    _cubit.getProductList(true);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      top: true,
      child: Scaffold(
        backgroundColor: R.color.grey300,
        appBar: appBar(context, R.string.cart.tr(), leftCallback: () => Navigator.pop(context)),
        body: BlocProvider(
          create: (_) => _cubit,
          child: BlocConsumer<ShoppingCartCubit, ShoppingCartState>(
            listener: (context, state) {
              if (state is ShoppingCartFailure) Util.showErrorSnackBar(context, state.error);
              if (!(state is ShoppingCartLoading)) _refreshController.refreshCompleted();
            },
            builder: (context, state) {
              return Scaffold(
                body: Stack(
                  children: [
                    SmartRefresher(
                        controller: _refreshController,
                        onRefresh: () {
                          _cubit.getProductList(true);
                        },
                        child: _buildPage(context, state)),
                  ],
                ),
              );
            },
          ),
        ),
      ),
    );
  }

  Widget _buildPage(BuildContext context, ShoppingCartState state) {
    int length = _cubit.getList().length;
    return Container(
      width: double.infinity,
      height: double.infinity,
      child: Stack(
        children: [
          Visibility(
            visible: length > 0,
            child: Column(
              children: [
                ListView.builder(
                  padding: const EdgeInsets.symmetric(vertical: 10),
                  shrinkWrap: true,
                  itemCount: length,
                  itemBuilder: (BuildContext context, int index) {
                    DetailProductData product = _cubit.getProduct(index);
                    return Card(
                      child: Padding(
                        padding: EdgeInsets.symmetric(horizontal: 10, vertical: 10),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.start,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            SizedBox(
                              width: 200.w,
                              height: 250.h,
                              child: Util.isEmpty(product.image)
                                  ? Image.asset(
                                      R.drawable.ic_health,
                                      fit: BoxFit.fill,
                                    )
                                  : CachedNetworkImage(
                                      imageUrl:
                                          Util.getImageUrl(product.image ?? "", host: "https://cdn.chiaki.vn/") ?? "",
                                      fit: BoxFit.fill,
                                    ),
                            ),
                            SizedBox(
                              width: 10,
                              height: 10,
                            ),
                            Expanded(
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: <Widget>[
                                  Padding(
                                    padding: EdgeInsets.only(right: 5.0),
                                    child: Row(
                                      mainAxisAlignment: MainAxisAlignment.start,
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        Expanded(
                                          child: Text(
                                            product.vietnameseName ?? "",
                                            maxLines: 2,
                                            textAlign: TextAlign.start,
                                            overflow: TextOverflow.ellipsis,
                                            style: TextStyle(
                                                fontSize: 16.sp, color: R.color.black, fontWeight: FontWeight.w600),
                                          ),
                                        ),
                                        InkWell(
                                          onTap: () {
                                            _cubit.delete(index, product.itemId!);
                                          },
                                          child: Icon(MdiIcons.close),
                                        ),
                                      ],
                                    ),
                                  ),
                                  SizedBox(
                                    height: 10,
                                  ),
                                  Row(
                                    mainAxisSize: MainAxisSize.min,
                                    crossAxisAlignment: CrossAxisAlignment.center,
                                    children: <Widget>[
                                      Text(
                                        Util.formatMoney(product.price),
                                        style:
                                            TextStyle(fontSize: 16.sp, fontWeight: FontWeight.w800, color: R.color.red),
                                      ),
                                      SizedBox(
                                        width: 10.0,
                                      ),
                                      Visibility(
                                        child: Text(
                                          Util.formatMoney(product.price),
                                          textAlign: TextAlign.center,
                                          style: TextStyle(
                                              fontSize: 16.sp,
                                              color: R.color.black,
                                              decoration: TextDecoration.lineThrough),
                                        ),
                                      ),
                                    ],
                                  ),
                                  SizedBox(
                                    height: 10,
                                  ),
                                  Row(
                                    mainAxisAlignment: MainAxisAlignment.start,
                                    children: <Widget>[
                                      InkWell(
                                        onTap: () {
                                          _cubit.decrement(index);
                                        },
                                        child: Container(
                                          child: Icon(
                                            MdiIcons.minusCircleOutline,
                                            color: product.price != 1 ? R.color.black : R.color.primaryColor,
                                            size: 80.h,
                                          ),
                                        ),
                                      ),
                                      SizedBox(width: 10),
                                      Container(
                                        child: Text(
                                          product.rowNumber!.round().toString(),
                                          textAlign: TextAlign.center,
                                          style: TextStyle(
                                              fontSize: 16.sp, color: R.color.black, fontWeight: FontWeight.w500),
                                        ),
                                      ),
                                      SizedBox(width: 10),
                                      InkWell(
                                        onTap: () {
                                          _cubit.increment(index);
                                        },
                                        child: Container(
                                          child: Icon(
                                            MdiIcons.plusCircleOutline,
                                            color: R.color.black,
                                            size: 80.h,
                                          ),
                                        ),
                                      ),
                                      Spacer(),
                                      InkWell(
                                        onTap: () {
                                          _cubit.delete(index, product.itemId!);
                                        },
                                        child: Container(
                                          padding: EdgeInsets.symmetric(horizontal: 10, vertical: 5),
                                          color: R.color.grey100,
                                          child: Center(
                                            child: Text(
                                              R.string.buy_again.tr(),
                                              style: TextStyle(fontSize: 16.sp, fontWeight: FontWeight.w600),
                                            ),
                                          ),
                                        ),
                                      ),
                                    ],
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
                    );
                  },
                ),
                SizedBox(height: 20),
                Container(
                  color: R.color.white,
                  padding: EdgeInsets.symmetric(horizontal: 15, vertical: 10),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        "Tạm Tính",
                        style: TextStyle(
                          fontSize: 16.sp,
                          fontWeight: FontWeight.w400,
                          color: R.color.grey500,
                        ),
                      ),
                      Text(
                        Util.formatMoney(_cubit.totalValue()),
                        style: TextStyle(
                          fontSize: 16.sp,
                          color: R.color.red,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
          Positioned(
              bottom: 0,
              right: 0,
              left: 0,
              child: Column(
                children: [
                  Divider(
                    height: 1,
                  ),
                  Container(
                    color: R.color.white,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: [
                        Container(
                          padding: EdgeInsets.symmetric(horizontal: 15),
                          child: RichText(
                            text: TextSpan(
                                text: R.string.total.tr(),
                                style: TextStyle(fontSize: 16.sp, color: R.color.grey500),
                                children: <TextSpan>[
                                  TextSpan(
                                    text: ( Util.formatMoney(_cubit.totalValue())),
                                    style: TextStyle(
                                      fontSize: 20.sp,
                                      color: R.color.red,
                                      fontWeight: FontWeight.w600,
                                    ),
                                  ),
                                ]),
                          ),
                        ),
                        Container(
                          padding: EdgeInsets.symmetric(horizontal: 15, vertical: 15),
                          color: R.color.red,
                          child: Center(
                            child: Text(
                              R.string.book.tr().toUpperCase(),
                              style: TextStyle(
                                fontSize: 16.sp,
                                fontWeight: FontWeight.w600,
                                color: R.color.white,
                              ),
                            ),
                          ),
                        )
                      ],
                    ),
                  ),
                ],
              )),
          Center(
            child: Visibility(
              visible: length == 0,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  CachedNetworkImage(
                    imageUrl: "https://voxephucthao.vn/css/skin/empty_cart.png",
                    height: 200.h,
                    width: 200.h,
                  ),
                  Text(
                    R.string.cart_empty.tr(),
                    style: TextStyle(
                      fontSize: 22.sp,
                      fontWeight: FontWeight.w600,
                      color: R.color.grey500,
                    ),
                  ),
                ],
              ),
            ),
          ),
          Visibility(
            visible: state is ShoppingCartLoading,
            child: PendingAction(),
          ),
        ],
      ),
    );
  }
}
