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/detail_category_response.dart';
import 'package:e_commerce_training/src/page/detail_category/detail_category_cubit.dart';
import 'package:e_commerce_training/src/page/detail_product/detail_product_page.dart';
import 'package:e_commerce_training/src/page/main/main_cubit.dart';
import 'package:e_commerce_training/src/page/search/search.dart';
import 'package:e_commerce_training/src/util/const.dart';
import 'package:e_commerce_training/src/util/navigation_util.dart';
import 'package:e_commerce_training/src/util/util.dart';
import 'package:e_commerce_training/src/widget/button_widget.dart';
import 'package:e_commerce_training/src/widget/star_widget.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.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';

class DetailCategory extends StatefulWidget {
  final int id;
  final String detailName;

  DetailCategory({required this.id, required this.detailName});

  @override
  _DetailCategoryState createState() => _DetailCategoryState();
}

class _DetailCategoryState extends State<DetailCategory> {
  late RowDetailCategoryCubit _cubit;
  RefreshController _refreshController = RefreshController();
  TextEditingController minController = TextEditingController();
  TextEditingController maxController = TextEditingController();
  late MainCubit _mainCubit;

  @override
  void initState() {
    // TODO: implement initState
    AppRepository repository = AppRepository();
    _cubit = RowDetailCategoryCubit(repository);
    super.initState();
    _cubit.getListDetailCategory(id: widget.id);
    _cubit.getListFilter();
  }

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (BuildContext context) => _cubit,
      child: Scaffold(
        appBar: AppBar(
          backgroundColor: R.color.primaryColor,
          iconTheme: IconThemeData(color: R.color.white),
          title: Row(
            children: [
              InkWell(
                child: Icon(Icons.arrow_back),
                onTap: () {
                  NavigationUtil.pop(context);
                },
              ),
              Expanded(
                child: InkWell(
                  onTap: () {
                    _mainCubit.selectTab(Const.SEARCH);
                    NavigationUtil.rootNavigatePage(context, SearchPage());
                  },
                  child: Container(
                    padding: EdgeInsets.symmetric(vertical: 5, horizontal: 10),
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(2),
                      color: R.color.white,
                    ),
                    child: Row(
                      children: [
                        Icon(
                          MdiIcons.magnify,
                          color: R.color.grey500,
                        ),
                        Expanded(
                          child: RichText(
                            overflow: TextOverflow.ellipsis,
                            text: TextSpan(
                              text: R.string.category.tr(),
                              style: TextStyle(fontSize: 16.sp, color: R.color.grey500),
                              children: <TextSpan>[
                                TextSpan(
                                  text: _cubit.detailCategoryData?.categoryName ?? widget.detailName,
                                  style: TextStyle(
                                    fontSize: 16.sp,
                                    color: R.color.blue,
                                    fontWeight: FontWeight.w500,
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
              SizedBox(width: 10),
              Icon(
                MdiIcons.cartMinus,
                color: R.color.white,
              ),
            ],
          ),
        ),
        endDrawerEnableOpenDragGesture: true,
        endDrawer: buildWidgetDrawer(),
        body: BlocProvider(
          create: (BuildContext context) => _cubit,
          child: BlocConsumer<RowDetailCategoryCubit, RowDetailCategoryState>(
            listener: (context, state) {
              if (state is DetailCategoryFailure) Util.showErrorSnackBar(context, state.error);
              if (!(state is DetailCategoryLoading)) {
                _refreshController.refreshCompleted();
                _refreshController.loadComplete();
              }
            },
            builder: (context, RowDetailCategoryState state) {
              DetailCategoryData? data = _cubit.detailCategoryData;
              return SmartRefresher(
                enablePullUp: true,
                controller: _refreshController,
                onRefresh: () => _cubit.getListDetailCategory(isRefresh: true),
                onLoading: () => _cubit.getListDetailCategory(isLoadMore: true),
                child: data == null
                    ? Center(
                        child: SizedBox(),
                      )
                    : SingleChildScrollView(
                        child: Column(
                          children: [
                            Container(
                              padding: EdgeInsets.symmetric(horizontal: 10),
                              child: Row(
                                children: [
                                  Text(
                                    R.string.latest.tr(),
                                    style: TextStyle(fontSize: 16.sp, color: R.color.black),
                                  ),
                                  SizedBox(
                                    width: 10,
                                  ),
                                  Container(
                                    color: R.color.grey,
                                    width: 1.w,
                                    height: 16.h,
                                  ),
                                  SizedBox(
                                    width: 10,
                                  ),
                                  Expanded(
                                    child: Text(
                                      R.string.fast_selling.tr(),
                                      style: TextStyle(fontSize: 16.sp, color: R.color.black),
                                    ),
                                  ),
                                  Text(
                                    R.string.price.tr(),
                                    style: TextStyle(fontSize: 16.sp, color: R.color.black),
                                  ),
                                  Icon(
                                    Icons.arrow_upward_outlined,
                                    size: 16.h,
                                  ),
                                  SizedBox(
                                    width: 10,
                                  ),
                                  Container(
                                    color: R.color.grey,
                                    width: 2.w,
                                    height: 40.h,
                                  ),
                                  SizedBox(
                                    width: 10,
                                  ),
                                  Icon(
                                    MdiIcons.filterOutline,
                                    size: 16.h,
                                  ),
                                  InkWell(
                                    onTap: () {
                                      Scaffold.of(context).openEndDrawer();
                                    },
                                    child: Text(
                                      R.string.filter.tr(),
                                      style: TextStyle(fontSize: 16.sp, color: R.color.black),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            // RowDetailCategory(),
                            Divider(
                              height: 1,
                              color: R.color.black,
                            ),
                            Container(
                              padding: EdgeInsets.symmetric(vertical: 10),
                              color: R.color.white,
                              height: 150.h,
                              child: ListView.builder(
                                shrinkWrap: true,
                                primary: true,
                                scrollDirection: Axis.horizontal,
                                itemCount: data.listNew!.length,
                                //_cubit.listDetail[_cubit.index].listDetailCategory!.listDetail!.length,
                                itemBuilder: (BuildContext context, int index) {
                                  return Container(
                                    padding: EdgeInsets.symmetric(horizontal: 5),
                                    width: 100.w,
                                    child: Column(
                                      mainAxisAlignment: MainAxisAlignment.center,
                                      children: [
                                        CachedNetworkImage(
                                          imageUrl: Util.getImageUrl(data.listNew?[index].imageUrl ?? "", host: "https://cdn.chiaki.vn/") ?? "",
                                          height: 100.h,
                                          width: 100.w,
                                        ),
                                        SizedBox(
                                          height: 5,
                                        ),
                                        Text("${data.listNew![index].name}",
                                            style: TextStyle(
                                              fontSize: 16.sp,
                                            ),
                                            maxLines: 1,
                                            overflow: TextOverflow.ellipsis,
                                            textAlign: TextAlign.center)
                                      ],
                                    ),
                                  );
                                },
                              ),
                            ),
                            data.imageUrl != null
                                ? CachedNetworkImage(
                                    imageUrl: Util.getImageUrl(data.imageUrl ?? "", host: "https://cdn.chiaki.vn/") ?? "",
                                    width: double.infinity,
                                    height: 200.h,
                                    fit: BoxFit.cover)
                                : SizedBox(),
                            SizedBox(
                              height: 10,
                            ),
                            GridView.count(
                              shrinkWrap: true,
                              primary: false,
                              crossAxisCount: 2,
                              childAspectRatio: 3 / 4,
                              children: List.generate(
                                data.listProduct!.length,
                                (index) {
                                  return InkWell(
                                    onTap: () {
                                      NavigationUtil.rootNavigatePage(
                                        context,
                                        DetailProductPage(
                                          id: data.id!,
                                          productName: data.categoryName ?? "",
                                        ),
                                      );
                                    },
                                    child: Stack(
                                      children: [
                                        Container(
                                          padding: EdgeInsets.symmetric(horizontal: 15),
                                          decoration: BoxDecoration(
                                            color: R.color.white,
                                            border: Border.all(width: 0.5, color: R.color.grey),
                                          ),
                                          child: Column(
                                            mainAxisAlignment: MainAxisAlignment.center,
                                            children: [
                                              CachedNetworkImage(
                                                height: 120.h,
                                                width: 80.w,
                                                fit: BoxFit.cover,
                                                imageUrl:
                                                    Util.getImageUrl(data.listProduct![index].imageUrl ?? "", host: "https://cdn.chiaki.vn/") ?? "",
                                              ),
                                              Text(
                                                "${data.listProduct![index].name}",
                                                maxLines: 2,
                                                overflow: TextOverflow.ellipsis,
                                                style: TextStyle(
                                                  fontSize: 16.sp,
                                                ),
                                              ),
                                              SizedBox(
                                                height: 5,
                                              ),
                                              Row(
                                                children: [
                                                  StarWidget(itemSize: 20),
                                                  SizedBox(
                                                    width: 5,
                                                  ),
                                                  Text(
                                                    "${data.listProduct![index].evaluate}",
                                                    style: TextStyle(
                                                      fontSize: 14.sp,
                                                    ),
                                                  )
                                                ],
                                              ),
                                              SizedBox(
                                                height: 5,
                                              ),
                                              Row(
                                                children: [
                                                  Text(
                                                    Util.formatMoney("${data.listProduct![index].price}"),
                                                    style: TextStyle(fontSize: 16.sp, fontWeight: FontWeight.bold, color: R.color.red),
                                                  ),
                                                  Spacer(),
                                                  Text(
                                                    Util.formatMoney("${data.listProduct![index].cost}"),
                                                    style: TextStyle(
                                                      fontSize: 16.sp,
                                                      color: R.color.grey500,
                                                      decoration: TextDecoration.lineThrough,
                                                      decorationThickness: 1.5,
                                                    ),
                                                  )
                                                ],
                                              ),
                                            ],
                                          ),
                                        ),
                                        Positioned(
                                          right: 0,
                                          top: 0,
                                          child: Container(
                                            height: 50.h,
                                            width: 50.h,
                                            child: Stack(
                                              children: [
                                                Image.asset(
                                                  R.drawable.circle,
                                                  color: R.color.red,
                                                ),
                                                Center(
                                                  child: Column(
                                                    children: [
                                                      Text(
                                                        "${data.listProduct![index].discount}",
                                                        style: TextStyle(
                                                          color: R.color.red,
                                                          fontWeight: FontWeight.w700,
                                                          fontSize: 16.sp,
                                                        ),
                                                      ),
                                                      Text(
                                                        R.string.off.tr(),
                                                        style: TextStyle(
                                                          color: R.color.red,
                                                          fontWeight: FontWeight.bold,
                                                          fontSize: 16.sp,
                                                        ),
                                                      ),
                                                    ],
                                                    mainAxisAlignment: MainAxisAlignment.center,
                                                  ),
                                                ),
                                              ],
                                            ),
                                          ),
                                        )
                                      ],
                                    ),
                                  );
                                },
                              ),
                            )
                          ],
                        ),
                      ),
              );
            },
          ),
        ),
      ),
    );
  }

  Widget buildWidgetDrawer() {
    return SafeArea(
      child: BlocBuilder<RowDetailCategoryCubit, RowDetailCategoryState>(
        builder: (context, state) {
          return Container(
            width: ScreenUtil.defaultSize.width,
            child: Drawer(
              child: Column(
                children: [
                  Padding(
                    padding: EdgeInsets.symmetric(horizontal: 10, vertical: 10),
                    child: Row(
                      children: [
                        Expanded(
                          child: Text(
                            R.string.filter_find.tr(),
                            style: TextStyle(fontSize: 16.sp, color: R.color.black, fontWeight: FontWeight.w400),
                          ),
                        ),
                        InkWell(
                          onTap: () {
                            _cubit.cleanDataAll();
                          },
                          child: Icon(MdiIcons.refresh),
                        ),
                      ],
                    ),
                  ),
                  Container(height: 1, color: R.color.grey),
                  Expanded(
                    child: ListView(
                      shrinkWrap: true,
                      children: [
                        Container(
                          margin: EdgeInsets.symmetric(horizontal: 15, vertical: 10),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                R.string.manufacturer.tr(),
                                style: TextStyle(fontSize: 16.sp),
                              ),
                              SizedBox(height: 10),
                              buildGridView(
                                posSelected: _cubit.positionManufacturer,
                              )
                            ],
                          ),
                        ),
                        InkWell(
                          onTap: () {
                            _cubit.setCheck();
                          },
                          child: _cubit.isCheck
                              ? Row(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    Text(
                                      R.string.show_more.tr(),
                                      style: TextStyle(fontSize: 15.sp),
                                    ),
                                    Icon(MdiIcons.chevronDown)
                                  ],
                                )
                              : Row(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    Text(
                                      R.string.collapse.tr(),
                                      style: TextStyle(fontSize: 15.sp),
                                    ),
                                    Icon(MdiIcons.chevronUp)
                                  ],
                                ),
                        ),
                        SizedBox(height: 10),
                      ],
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.symmetric(horizontal: 10, vertical: 10),
                    child: ButtonWidget(
                      backgroundColor: R.color.primaryColor,
                      title: R.string.apply_now.tr(),
                      onPressed: () {},
                    ),
                  )
                ],
              ),
            ),
          );
        },
      ),
    );
  }

  Widget buildGridView({required List<int> posSelected}) {
    return GridView.count(
      shrinkWrap: true,
      physics: NeverScrollableScrollPhysics(),
      childAspectRatio: 4 / 1,
      crossAxisCount: 2,
      crossAxisSpacing: 15,
      mainAxisSpacing: 10,
      children: List.generate(
        _cubit.isCheck ? 4 : _cubit.listFilter.length,
        (index) {
          bool isSelected = posSelected.contains(index);
          return InkWell(
            onTap: () {
              _cubit.onChangeManufacturer(index);
            },
            child: Container(
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(3),
                border: Border.all(color: isSelected ? R.color.primaryColor : R.color.grey),
                color: isSelected ? R.color.primaryColor : R.color.grey200,
              ),
              child: Center(
                child: Text(
                  _cubit.listFilter[index].vietnameseName ?? "",
                  style: TextStyle(color: R.color.black, fontSize: 15.sp),
                ),
              ),
            ),
          );
        },
      ),
    );
  }
}
