import 'package:boilerplate/core/i18n/translations.g.dart';
import 'package:boilerplate/core/styles/my_dimensions.dart';
import 'package:boilerplate/core/styles/my_font.dart';
import 'package:boilerplate/presentation/widgets/ipm_data_not_found.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../../../../core/di/injection_init.dart';
import '../../../../../core/styles/my_colors.dart';
import '../../../../../core/utils/shared_preferences_util.dart';
import '../../../../bloc/products_list/products_bloc.dart';
import '../../../../widgets/ipm_image.dart';

class ProductListResult extends StatefulWidget {
  final bool showRefresh;
  final String? myTitle;
  final String? searchTxt;
  ProductListResult(
      {Key? key, this.showRefresh = true, this.myTitle, this.searchTxt})
      : super(key: key);

  @override
  State<ProductListResult> createState() => _ProductListResultState();
}

class _ProductListResultState extends State<ProductListResult> {
  final GlobalKey<RefreshIndicatorState> refreshKey =
      GlobalKey<RefreshIndicatorState>();
  late String? count = "0";
  bool _isLoadMore = true;
  late String lang = '';

  @override
  void initState() {
    super.initState();

    if (widget.showRefresh) {
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
        refreshKey.currentState?.show();
      });
    }
    getLang();
    // final pref = getIt.get<SharedPreferencesUtil>();
    //
    // int i = pref.getInt(SharedPreferencesUtil.keyListCount) ?? 0;
    // count = i.toString();
  }

  getLang() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();

    setState(() {
      lang = prefs.getString('lang').toString();
    });
  }

  Future<bool> _onRefresh() async {
    var bloc = context.read<ProductListBloc>()..add(RefreshEvent());
    var state = await bloc.stream.firstWhere((state) =>
        state is GetProductsSuccessState || state is GetProductsFailState);
    return state is GetProductsSuccessState || state is GetProductsFailState;
  }

  bool _onLintener(ScrollNotification notification) {
    if (!_isLoadMore &&
        (notification.metrics.pixels >
            notification.metrics.maxScrollExtent * 0.7)) {
      _isLoadMore = true;

      BlocProvider.of<ProductListBloc>(context).add(LoadMoreEvent());
    }

    return true;
  }

  void _blocListener(BuildContext context, ProductListState state) {
    if (state is GetProductsSuccessState) {
      _isLoadMore = !state.data.canLoadMore;
    } else if (state is SumitFilterState || state is ShowRefreshState) {
      refreshKey.currentState?.show();
    }
    setState(() {
      final pref = getIt.get<SharedPreferencesUtil>();

      int i = pref.getInt(SharedPreferencesUtil.keyListCount) ?? 0;
      count = i.toString();
    });
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Expanded(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: EdgeInsets.only(
              top: MyDimens.dimen16,
              left: MyDimens.dimen16,
              bottom: MyDimens.dimen8,
            ),
            child: RichText(
              textAlign: TextAlign.start,
              text: TextSpan(
                children: [
                  TextSpan(
                    text: widget.myTitle,
                    style: MyFont.medium18,
                  ),
                  TextSpan(
                    text: lang == "th" || lang == ""
                        ? AppLocalizations.products.all
                        : AppLocalizations.products.all_idea_en,
                    style: MyFont.medium18.copyWith(
                      color: Color(0xFFF15B44),
                    ),
                  ),
                ],
              ),
            ),
          ),
          Padding(
            padding: EdgeInsets.only(
              top: 0,
              left: MyDimens.dimen16,
              bottom: MyDimens.dimen16,
            ),
            child: Text(
              lang == "th" || lang == ""
                  ? 'รายการทั้งหมด ${count}'
                  : "total ${count}",
              style: MyFont.medium14.copyWith(color: Colors.black87),
            ),
          ),
          _list(),
          // widget.searchTxt ==""||widget.searchTxt==null?_list() :  _listNew(),
        ],
      ),
    );
  }

  Widget _list() {
    return Expanded(
      child: BlocConsumer<ProductListBloc, ProductListState>(
        listener: _blocListener,
        builder: (context, state) {
          return NotificationListener<ScrollNotification>(
            onNotification: _onLintener,
            child: RefreshIndicator(
              key: refreshKey,
              onRefresh: _onRefresh,
              color: MyColor.orange,
              child: Stack(
                children: [
                  GridView.builder(
                    padding: EdgeInsets.only(
                      bottom: MyDimens.dimen16,
                      left: MyDimens.dimen16,
                      right: MyDimens.dimen16,
                    ),
                    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 2,
                      childAspectRatio: 7.8 / 13.2,
                      mainAxisSpacing: MyDimens.dimen14,
                      crossAxisSpacing: MyDimens.dimen24,
                    ),
                    itemCount: state.data.products.length,
                    itemBuilder: (context, index) {
                      final item = state.data.products[index];

                      return GestureDetector(
                        onTap: () {
                          // print("onclick => ${item}");
                          BlocProvider.of<ProductListBloc>(context)
                              .add(SelectProductEvent(item));
                        },
                        child: Container(
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(10),
                            boxShadow: [
                              BoxShadow(
                                color: Colors.black.withOpacity(0.2),
                                blurRadius: 5,
                                offset: const Offset(1, 4),
                              )
                            ],
                          ),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.start,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Container(
                                width: MyDimens.dimen160,
                                height: MyDimens.dimen164,
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(8),
                                ),
                                child: ClipRRect(
                                  borderRadius: BorderRadius.circular(0),
                                  child: IPMImage(
                                    url: item.cover ?? '',
                                    fit: BoxFit.cover,
                                  ),
                                ),
                              ),
                              SizedBox(height: MyDimens.dimen8),
                              Container(
                                margin: EdgeInsets.only(left: 8, right: 8),
                                child: SizedBox(
                                  height: 40,
                                  width: MyDimens.dimen160,
                                  child: Text(
                                    item.name ?? '',
                                    // textAlign: TextAlign.center,
                                    style: MyFont.regular14.copyWith(
                                      color: MyColor.headerColor,
                                      overflow: TextOverflow.ellipsis,
                                    ),
                                    maxLines: 2,
                                  ),
                                ),
                              ),
                              Container(
                                child: Divider(),
                                margin: EdgeInsets.only(left: 8, right: 8),
                              ),
                              Container(
                                alignment: Alignment.topLeft,
                                margin: EdgeInsets.only(
                                    left: 8, right: 8, top: 8, bottom: 8),
                                decoration: BoxDecoration(
                                  color: Colors.white,
                                  borderRadius: BorderRadius.circular(5),
                                  boxShadow: [
                                    BoxShadow(
                                      color: Colors.black.withOpacity(0.2),
                                      blurRadius: 5,
                                      offset: const Offset(1, 4),
                                    )
                                  ],
                                ),
                                width: MyDimens.dimen80,
                                height: MyDimens.dimen24,
                                child: SizedBox(
                                  width: MyDimens.dimen80,
                                  child: Text(
                                    lang == "th" || lang == ""
                                        ? 'รายละเอียด'
                                        : "Detail",
                                    textAlign: TextAlign.center,
                                    style: MyFont.regular12.copyWith(
                                      color: MyColor.headerColor,
                                      overflow: TextOverflow.ellipsis,
                                    ),
                                    maxLines: 1,
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                      );
                    },
                  ),
                  if ((state is GetProductsSuccessState ||
                          state is GetProductsFailState) &&
                      state.data.products.length == 0)
                    IPMDataNotFound(),
                ],
              ),
            ),
          );
        },
      ),
    );
  }

  Widget _listNew() {
    return Expanded(
      child: BlocConsumer<ProductListBloc, ProductListState>(
        listener: _blocListener,
        builder: (context, state) {
          return NotificationListener<ScrollNotification>(
            onNotification: _onLintener,
            child: RefreshIndicator(
              key: refreshKey,
              onRefresh: _onRefresh,
              color: MyColor.orange,
              child: Stack(
                children: [
                  ListView.builder(
                    padding: EdgeInsets.only(
                      bottom: MyDimens.dimen16,
                      left: MyDimens.dimen16,
                      right: MyDimens.dimen16,
                    ),
                    // gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                    //   crossAxisCount: 1,
                    //   childAspectRatio: 1,
                    //   // childAspectRatio: 7.8 / 13.2,
                    //   // mainAxisSpacing: MyDimens.dimen14,
                    //   // crossAxisSpacing: MyDimens.dimen24,
                    // ),
                    itemCount: 5,
                    itemBuilder: (context, index) {
                      final item = state.data.products[index];

                      return GestureDetector(
                        onTap: () {
                          // print("onclick => ${item}");
                          BlocProvider.of<ProductListBloc>(context)
                              .add(SelectProductEvent(item));
                        },
                        child: Column(
                          children: [
                            Container(
                              // height: 50,

                              child: Text(
                                item.name ?? '',
                                // textAlign: TextAlign.center,
                                style: MyFont.regular14.copyWith(
                                  color: MyColor.headerColor,
                                  overflow: TextOverflow.ellipsis,
                                ),
                                maxLines: 2,
                              ),
                            ),
                            Divider(),
                          ],
                        ),
                      );
                    },
                  ),
                  if ((state is GetProductsSuccessState ||
                          state is GetProductsFailState) &&
                      state.data.products.length == 0)
                    IPMDataNotFound(),
                ],
              ),
            ),
          );
        },
      ),
    );
  }
}
