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/list_community_response.dart';
import 'package:e_commerce_training/src/util/util.dart';
import 'package:easy_localization/src/public_ext.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import 'choose_category_cubit.dart';
import 'choose_category_state.dart';

class ChooseCategoryPage extends StatefulWidget {
  @override
  _ChooseCategoryPageState createState() => _ChooseCategoryPageState();
}

class _ChooseCategoryPageState extends State<ChooseCategoryPage> {
  late ChooseCategoryCubit _cubit;
  final RefreshController _refreshController = RefreshController();

  @override
  void initState() {
    // TODO: implement initState
    AppRepository repository = AppRepository();
    _cubit = ChooseCategoryCubit(repository);
    _cubit.getListCategory();
    _cubit.getListCommunity();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: BlocProvider(
        create: (context) => _cubit,
        child: BlocConsumer<ChooseCategoryCubit, ChooseCategoryState>(
          listener: (context, state) {
            if (state is! ChooseCategoryLoading) {
              _refreshController.refreshCompleted();
            }
            if (state is ChooseCategoryFailure) Util.showErrorSnackBar(context, state.error);
          },
          builder: (context, state) {
            return buildPage(context, state);
          },
        ),
      ),
    );
  }

  Widget buildPage(BuildContext context, ChooseCategoryState state) {
    return Stack(
      children: [
        SmartRefresher(
          controller: _refreshController,
          onRefresh: () {
            _cubit.getListCategory(isRefresh: true);
            _cubit.getListCommunity(isRefresh: true);
          },
          child: ListView(
            padding: EdgeInsets.all(20.h),
            shrinkWrap: true,
            children: [
              SizedBox(height: 30.h),
              Center(
                child: Text(
                  R.string.choose_your_favorite_contents.tr(),
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    fontSize: 19.sp,
                    fontWeight: FontWeight.w600,
                    color: R.color.black,
                  ),
                ),
              ),
              SizedBox(height: 10.h),
              Center(
                child: Text(
                  R.string.choose_the_best.tr(),
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    fontSize: 12.sp,
                    color: R.color.black,
                  ),
                ),
              ),
              SizedBox(height: 30.h),
              categoryWidget(),
              SizedBox(height: 35.h),
              Center(
                child: Text(
                  R.string.choose_your_favorite.tr(),
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    fontSize: 19.sp,
                    fontWeight: FontWeight.w600,
                    color: R.color.black,
                  ),
                ),
              ),
              SizedBox(height: 10.h),
              Center(
                child: Text(
                  R.string.choose_the_best_favorite.tr(),
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    fontSize: 12.sp,
                    color: R.color.black,
                  ),
                ),
              ),
              SizedBox(height: 30.h),
              communityWidget(),
              SizedBox(height: 120.h),
            ],
          ),
        ),
        // Positioned(
        //     left: 0,
        //     bottom: 0,
        //     right: 0,
        // child: BottomButtonWidget(
        //     text: R.string.done.tr(),
        //     onTap: () => NavigationUtil.pushAndRemoveUtilPage(
        //         context, WelcomePage()))),
      ],
    );
  }

  Widget categoryWidget() {
    return Wrap(
      spacing: 15.h,
      runSpacing: 15.h,
      children: _cubit.listCategory.map((e) {
        bool isSelected = _cubit.listSelectedCategory.indexWhere((element) => element.id == e.id) >= 0;
        return InkWell(
          onTap: () {
            _cubit.selectCategory(e);
          },
          child: Container(
            padding: EdgeInsets.symmetric(horizontal: 20.h, vertical: 8.h),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(30.h),
              color: isSelected ? Util.parseStringToColor(e.color!) : R.color.white,
              boxShadow: [
                BoxShadow(
                  color: R.color.grey100,
                  spreadRadius: 0,
                  blurRadius: 5,
                  offset: Offset(0, 3), // changes position of shadow
                ),
              ],
            ),
            child: Text(
              e.title ?? "",
              style: TextStyle(
                  fontSize: 12.sp,
                  fontWeight: FontWeight.w600,
                  color: isSelected ? R.color.orange : Util.parseStringToColor(e.color!)),
            ),
          ),
        );
      }).toList(),
    );
  }

  Widget communityWidget() {
    return GridView.builder(
      shrinkWrap: true,
      padding: EdgeInsets.zero,
      itemCount: _cubit.listCommunity.length,
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisSpacing: 15.h, mainAxisSpacing: 15.h, crossAxisCount: 2, childAspectRatio: 150 / 220),
      itemBuilder: (context, index) {
        CommunityData data = _cubit.listCommunity[index];
        bool isSelected = _cubit.listSelectedCommunity.indexWhere((element) => element.id == data.id) >= 0;
        return InkWell(
          onTap: () {
            _cubit.selectCommunity(data);
          },
          child: Stack(
            children: [
              Container(
                decoration: BoxDecoration(
                    color: R.color.white,
                    border: Border.all(color: isSelected ? R.color.primaryColor : R.color.gray, width: 1),
                    borderRadius: BorderRadius.circular(5.h)),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Expanded(
                      child: ClipRRect(
                        borderRadius: BorderRadius.circular(5.h),
                        child: CachedNetworkImage(
                          imageUrl: "https://aphoto.vn/wp-content/uploads/2019/02/hinh8-16.jpg",
                          fit: BoxFit.cover,
                        ),
                      ),
                    ),
                    SizedBox(
                      height: 12.h,
                    ),
                    Padding(
                      padding: EdgeInsets.only(left: 12.h),
                      child: Text(
                        data.title ?? "",
                        textAlign: TextAlign.left,
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                          fontSize: 16.sp,
                          fontWeight: FontWeight.w600,
                          color: R.color.gray,
                        ),
                      ),
                    ),
                    SizedBox(
                      height: 6.h,
                    ),
                    Padding(
                      padding: EdgeInsets.only(left: 12.h),
                      child: Row(
                        children: [
                          Text(
                            data.number ?? "",
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                            style: TextStyle(
                              fontSize: 14.sp,
                              fontWeight: FontWeight.w600,
                              color: R.color.orange,
                            ),
                            textAlign: TextAlign.left,
                          ),
                          SizedBox(width: 5.h),
                          Text(
                            data.unit ?? "",
                            style: TextStyle(
                              fontSize: 10.sp,
                              fontWeight: FontWeight.w500,
                              color: R.color.gray,
                            ),
                            textAlign: TextAlign.left,
                          ),
                        ],
                      ),
                    ),
                    SizedBox(height: 12.h),
                  ],
                ),
              ),
              Positioned(
                  top: 8.h,
                  right: 8.h,
                  child: Container(
                    padding: EdgeInsets.all(12.h),
                    decoration: BoxDecoration(color: R.color.white, borderRadius: BorderRadius.circular(10.h)),
                    child: Icon(
                      Icons.perm_identity,
                      color: R.color.primaryColor,
                      size: 20.h,
                    ),
                  ))
            ],
          ),
        );
      },
    );
  }
}
