import 'package:boilerplate/core/di/injection_init.dart';
import 'package:boilerplate/core/utils/navigator_util.dart';
import 'package:boilerplate/presentation/bloc/favorite/favorites_bloc.dart';
import 'package:boilerplate/presentation/screen/products/detail/product_detail_screen.dart';
import 'package:boilerplate/presentation/widgets/base_scaffold.dart';
import 'package:firebase_analytics/firebase_analytics.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../../../core/styles/my_colors.dart';
import '../../../../core/styles/my_dimensions.dart';
import '../../../../core/styles/my_font.dart';
import '../../../widgets/ipm_data_not_found.dart';
import '../../../widgets/ipm_image.dart';

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

  @override
  State<FavoritesScreen> createState() => _FavoritesScreenState();
}

class _FavoritesScreenState extends State<FavoritesScreen> {
  final _refreshKey = GlobalKey<RefreshIndicatorState>();

  late final FavoritesBloc _bloc;
  late String lang = '';

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

    _bloc = getIt.get<FavoritesBloc>();

    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      _refreshKey.currentState?.show();
    });
    getLang();
  }

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

    setState(() {
      lang = prefs.getString('lang').toString();
    });
    await FirebaseAnalytics.instance.logScreenView(screenName: 'FavoritePage');
  }

  void _blocListener(BuildContext context, FavoritesState state) {
    if (state is SelectedFavoriteState) {
      NavigatorUtil.pushToPage(ProductDetailScreen(
        prodictId: state.productId,
      ));
    }
  }

  Future<bool> _onRefresh() async {
    _bloc..add(GetFavoritesEvent());
    var state = await _bloc.stream.firstWhere((state) =>
        state is GetFavoritesSuccessState || state is GetFavoritesFailState);
    return state is GetFavoritesSuccessState || state is GetFavoritesFailState;
  }

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

  @override
  Widget build(BuildContext context) {
    return BaseScaffold(
      title: lang == "th" || lang == "" ? 'ผลงานที่ถูกใจ' : "Favorite",
      body: BlocConsumer<FavoritesBloc, FavoritesState>(
        listener: _blocListener,
        bloc: _bloc,
        builder: (context, state) {
          return RefreshIndicator(
            key: _refreshKey,
            onRefresh: _onRefresh,
            color: MyColor.orange,
            child: Stack(
              children: [
                GridView.builder(
                  padding: EdgeInsets.all(MyDimens.dimen16).copyWith(
                    bottom: MediaQuery.of(context).padding.bottom +
                        MyDimens.dimen16,
                  ),
                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 2,
                    childAspectRatio: 7.8 / 10,
                    mainAxisSpacing: MyDimens.dimen14,
                    crossAxisSpacing: MyDimens.dimen24,
                  ),
                  itemCount: state.data.favs.length,
                  itemBuilder: (context, index) {
                    final item = state.data.favs[index];

                    return GestureDetector(
                      onTap: () {
                        _bloc.add(SelectFavoriteEvent(item.productId));
                      },
                      child: Column(
                        children: [
                          Container(
                            width: MyDimens.dimen160,
                            height: MyDimens.dimen164,
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(8),
                            ),
                            child: ClipRRect(
                              borderRadius: BorderRadius.circular(8),
                              child: IPMImage(
                                url: item.product.cover ?? '',
                                fit: BoxFit.cover,
                              ),
                            ),
                          ),
                          SizedBox(height: MyDimens.dimen8),
                          SizedBox(
                            width: MyDimens.dimen160,
                            child: Text(
                              item.product.name ?? '',
                              style: MyFont.regular12.copyWith(
                                color: MyColor.headerColor,
                                overflow: TextOverflow.ellipsis,
                              ),
                              maxLines: 2,
                            ),
                          ),
                        ],
                      ),
                    );
                  },
                ),
                if ((state is GetFavoritesSuccessState ||
                        state is GetFavoritesFailState) &&
                    state.data.favs.length == 0)
                  IPMDataNotFound(),
              ],
            ),
          );
        },
      ),
    );
  }
}
