import 'dart:async';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:e_commerce_training/res/R.dart';
import 'package:e_commerce_training/src/model/response/list_product_response.dart';
import 'package:e_commerce_training/src/model/response/product_detail_response.dart';
import 'package:e_commerce_training/src/page/detail_category/detail_category.dart';
import 'package:e_commerce_training/src/page/detail_product/detail_product_page.dart';
import 'package:e_commerce_training/src/page/main/main.dart';
import 'package:e_commerce_training/src/page/search/search_cubit.dart';
import 'package:e_commerce_training/src/page/search/search_state.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/empty_widget.dart';
import 'package:e_commerce_training/src/widget/pending_action.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_bloc/flutter_bloc.dart';
import 'package:flutter_rating_bar/flutter_rating_bar.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class SearchPage extends StatefulWidget {
  const SearchPage({Key? key}) : super(key: key);

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

class _SearchPageState extends State<SearchPage> {
  late MainCubit _mainCubit;
  late SearchCubit _cubit;
  RefreshController _refreshController = RefreshController();
  TextEditingController _searchController = TextEditingController();
  late DetailProductResponse data;
  Timer? _debounce;
  late List<String> suggestionKeyword = _mainCubit.searchKeyword.split(",");
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _mainCubit = BlocProvider.of<MainCubit>(context);
    _mainCubit.searchKeyword.split(",");
    _cubit = BlocProvider.of<SearchCubit>(context);
    _cubit.searchByKeyboard(_searchController.text.trim());
    _cubit.listProductSuggest();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: R.color.grey100,
        appBar: AppBar(
          backgroundColor: R.color.primaryColor,
          automaticallyImplyLeading: false,
          iconTheme: IconThemeData(color: R.color.white),
          title: Row(
            children: [
              Expanded(
                child: Container(
                  padding: EdgeInsets.symmetric(vertical: 10, horizontal: 10),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(2),
                    color: R.color.white,
                  ),
                  child: TextField(
                      autofocus: true,
                      textInputAction: TextInputAction.search,
                      controller: _searchController,
                      cursorColor: R.color.primaryColor,
                      decoration: InputDecoration.collapsed(
                        hintText: R.string.search_category.tr(),
                        border: InputBorder.none,
                      ),
                      onChanged: _onSearchChanged),
                ),
              ),
              SizedBox(width: 10),
              InkWell(
                onTap: () {
                  _mainCubit.selectTab(Const.HOME);
                },
                child: Text(
                  R.string.exit.tr(),
                  style: TextStyle(
                    fontSize: 16.sp,
                    fontWeight: FontWeight.w400,
                  ),
                ),
              ),
            ],
          ),
        ),
        body: BlocProvider(
            create: (_) => _cubit,
            child: BlocConsumer<SearchCubit, SearchState>(
              listener: (BuildContext context, state) {
                if (state is SearchFailure) {
                  Util.showErrorSnackBar(context, state.error);
                }
                if (!(state is SearchLoading)) {
                  _refreshController.refreshCompleted();
                }
              },
              builder: (context, state) {
                return GestureDetector(
                  onTap: () => Util.hideKeyboard(context),
                  child: Stack(
                    children: <Widget>[
                      SmartRefresher(
                        controller: _refreshController,
                        onRefresh: () => _cubit.getSuggestSearch(isRefresh: true),
                        onLoading: () => _cubit.getSuggestSearch(isLoadMore: true),
                        child: Container(
                            height: double.infinity,
                            color: R.color.white,
                            child: !Util.isEmpty(_searchController.text)
                                ? buildListProduct()
                                : Column(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      Padding(
                                        padding: EdgeInsets.symmetric(horizontal: 15, vertical: 10),
                                        child: Text(
                                          R.string.popular_search.tr(),
                                          style: TextStyle(
                                            fontSize: 16.sp,
                                            fontWeight: FontWeight.w600,
                                            color: R.color.black,
                                          ),
                                        ),
                                      ),
                                      Container(
                                        padding: EdgeInsets.symmetric(horizontal: 15),
                                        child: buildListSuggest(),
                                      ),
                                    ],
                                  )),
                      ),
                      Visibility(
                        visible: state is SearchLoading,
                        child: PendingAction(),
                      ),
                    ],
                  ),
                );
              },
            )));
  }

  void _onSearchChanged(String text) {
    if (_debounce?.isActive ?? false) _debounce!.cancel();
    _debounce = Timer(const Duration(milliseconds: 500), () {
      _cubit.searchByKeyboard(text.trim());
    });
  }

  @override
  void dispose() {
    _debounce?.cancel();
    super.dispose();
  }

  Widget buildListSuggest() {
    return Wrap(
      spacing: 15,
      runSpacing: 15,
      children: List<Widget>.generate(suggestionKeyword.length, (int index) {
        return InkWell(
          onTap: () {
            _searchController.text = suggestionKeyword[index];
          },
          child: Container(
            padding: EdgeInsets.symmetric(horizontal: 10, vertical: 10),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(8),
              color: R.color.grey100,
            ),
            child: Text(
              suggestionKeyword[index],
              style: TextStyle(
                fontSize: 16.sp,
                fontWeight: FontWeight.w400,
                color: R.color.black,
              ),
            ),
          ),
        );
      }),
    );
  }

  Widget buildListProduct() {
    List<ListProductData> listProduct = _cubit.searchListProduct;
    bool emptySearch = Util.isEmpty(listProduct);
    return Column(
      children: [
        Container(
          margin: EdgeInsets.symmetric(horizontal: 10, vertical: 10),
          child: Row(
            children: [
              Expanded(
                child: Text(
                  R.string.suggest_product.tr(),
                  style: TextStyle(fontSize: 16.sp, color: R.color.black, fontWeight: FontWeight.w600),
                ),
              ),
              Visibility(
                visible: !emptySearch,
                child: InkWell(
                  onTap: () {},
                  child: Text(
                    R.string.more.tr(),
                    style: TextStyle(fontSize: 16.sp, color: R.color.primaryColor),
                  ),
                ),
              )
            ],
          ),
        ),
        Expanded(
            child: emptySearch
                ? Center(
                    child: EmptyWidget(R.string.cart_empty.tr()),
                  )
                : ListView.separated(
                    shrinkWrap: true,
                    itemBuilder: (BuildContext context, int index) {
                      ListProductData data = _cubit.searchListProduct[index];
                      return InkWell(
                        onTap: () {
                          NavigationUtil.rootNavigatePage(
                            context,
                            DetailProductPage(id: data.itemId!, productName: data.vietnameseName ?? ""),
                          );
                        },
                        child: Container(
                          padding: EdgeInsets.symmetric(vertical: 5, horizontal: 5),
                          width: MediaQuery.of(context).size.width,
                          child: Row(
                            children: [
                              CachedNetworkImage(
                                height: 100.h,
                                width: 80.w,
                                imageUrl: Util.getImageUrl(data.image ?? "", host: "https://cdn.chiaki.vn/") ?? "",
                              ),
                              SizedBox(
                                width: 5,
                              ),
                              Expanded(
                                child: Column(
                                  mainAxisAlignment: MainAxisAlignment.start,
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text(
                                      data.vietnameseName ?? "",
                                      style: TextStyle(fontSize: 16.sp),
                                      maxLines: 2,
                                    ),
                                    SizedBox(height: 5),
                                    Row(
                                      children: [
                                        Text(
                                          R.string.producer.tr(),
                                          style: TextStyle(fontSize: 14.sp, color: R.color.grey500),
                                        ),
                                        SizedBox(
                                          width: 5,
                                        ),
                                        Text(
                                          data.brandName ?? "",
                                          style: TextStyle(fontSize: 14.sp, color: R.color.black),
                                        ),
                                      ],
                                    ),
                                    SizedBox(height: 5),
                                    Text(
                                      Util.formatMoney(
                                        "${data.maxPrice}",
                                      ),
                                      style: TextStyle(color: R.color.red),
                                    ),
                                    SizedBox(height: 5),
                                    Row(
                                      children: [
                                        StarWidget(itemSize: 20),
                                        SizedBox(
                                          width: 3,
                                        ),
                                        Expanded(
                                          child: Text(
                                            data.createName ?? "",
                                            style: TextStyle(fontSize: 14.sp, color: R.color.grey500),
                                          ),
                                        )
                                      ],
                                    ),
                                  ],
                                ),
                              )
                            ],
                          ),
                        ),
                      );
                    },
                    separatorBuilder: (BuildContext context, int index) => Divider(
                          color: R.color.grey500,
                        ),
                    itemCount: _cubit.searchListProduct.length))
      ],
    );
  }
}
