import 'package:farm_tpf/data/repository/repository.dart';
import 'package:farm_tpf/presentation/custom_widgets/bottom_loader.dart';
import 'package:farm_tpf/presentation/custom_widgets/loading_list_page.dart';
import 'package:farm_tpf/presentation/screens/plot/widget_search.dart';
import 'package:farm_tpf/presentation/screens/plot_detail/sc_plot_detail.dart';
import 'package:farm_tpf/utils/pref.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:farm_tpf/utils/const_string.dart';

import '../../../models/item_dropdown.dart';
import '../../../utils/helpers.dart';
import '../../custom_widgets/dropdown/multiple_select_bottom_sheet.dart';
import 'bloc/plot_bloc.dart';
import 'widgets/item_plot.dart';

class PlotListScreen extends StatefulWidget {
  @override
  _PlotListScreenState createState() => _PlotListScreenState();
}

class _PlotListScreenState extends State<PlotListScreen> {
  final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
  var pref = LocalPref();
  var token;
  var client;
  String pushkey = "";
  String currentFullName = "";
  PlotBloc bloc = PlotBloc(repository: Repository());
  final _scrollController = ScrollController();
  final _scrollThreshold = 250.0;

  @override
  void initState() {
    super.initState();
    bloc.preparedData();
    bloc.add(DataFetched());
    _scrollController.addListener(() {
      final maxScroll = _scrollController.position.maxScrollExtent;
      final currentScroll = _scrollController.position.pixels;
      if (maxScroll - currentScroll < _scrollThreshold) {
        bloc.add(DataFetched());
      }
    });
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      key: _scaffoldKey,
      body: SafeArea(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            SizedBox(
              height: 8,
            ),
            Container(
              padding: EdgeInsets.all(8),
              color: Colors.white,
              child: Text(
                'Danh sách lô trồng',
                style: TextStyle(fontWeight: FontWeight.w500, fontSize: 22),
              ),
            ),
            WidgetSearch(
              searchController: bloc.searchCtl,
              onPressed: (value) {
                FocusScope.of(context).requestFocus(FocusNode());
                bloc.add(OnRefresh());
              },
            ),
            Row(
              children: [
                ValueListenableBuilder<List<ItemDropDown>>(
                  valueListenable: bloc.selectedSupply,
                  builder: (context, selecteds, _) {
                    return ValueListenableBuilder<List<ItemDropDown>>(
                      valueListenable: bloc.supplies,
                      builder: (context, status, _) {
                        return MultipleSelectBottomSheet(
                          dataSources: status,
                          initValue: selecteds,
                          onSelected: (val) {
                            bloc.selectedSupply.value = val;
                            Helpers.hideKeyboard(context);
                            bloc.add(OnRefresh());
                          },
                          hint: 'Giống',
                        );
                      },
                    );
                  },
                ),
                ValueListenableBuilder<List<ItemDropDown>>(
                  valueListenable: bloc.selectedArea,
                  builder: (context, selecteds, _) {
                    return ValueListenableBuilder<List<ItemDropDown>>(
                      valueListenable: bloc.areas,
                      builder: (context, status, _) {
                        return MultipleSelectBottomSheet(
                          dataSources: status,
                          initValue: selecteds,
                          onSelected: (val) {
                            bloc.selectedArea.value = val;
                            Helpers.hideKeyboard(context);
                            bloc.add(OnRefresh());
                          },
                          hint: 'Khu vực',
                        );
                      },
                    );
                  },
                ),
              ],
            ),
            Expanded(
                child: BlocBuilder<PlotBloc, PlotState>(
              bloc: bloc,
              builder: (context, state) {
                if (state is PlotFailure) {
                  return Center(child: Text(state.errorString));
                }
                if (state is PlotSuccess) {
                  if ((state.items ?? []).isEmpty) {
                    return Center(child: Text(label_list_empty));
                  }
                  return RefreshIndicator(
                    child: ListView.builder(
                      physics: AlwaysScrollableScrollPhysics(),
                      itemBuilder: (BuildContext context, int index) {
                        return index >= (state.items ?? []).length
                            ? BottomLoader()
                            : ItemPlot(
                                item: state.items?[index],
                                onPressed: () {
                                  Navigator.push(
                                    context,
                                    MaterialPageRoute(
                                      builder: (BuildContext context) => PlotDetailScreen(
                                        cropId: state.items?[index].id ?? -1,
                                        initialIndex: 0,
                                        cropType: state.items?[index].tbCropTypeId ?? -1,
                                      ),
                                    ),
                                  );
                                },
                              );
                      },
                      itemCount: (state.hasReachedMax ?? false) ? (state.items ?? []).length : (state.items ?? []).length + 1,
                      controller: _scrollController,
                    ),
                    onRefresh: () async {
                      bloc.add(OnRefresh());
                    },
                  );
                }
                return Center(
                  child: LoadingListPage(),
                );
              },
            ))
          ],
        ),
      ),
    );
  }
}
