import 'dart:async';

import 'package:farm_tpf/custom_model/EnvironmentParameter.dart';
import 'package:farm_tpf/data/repository/repository.dart';
import 'package:farm_tpf/presentation/custom_widgets/app_bar_widget.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/utils/const_color.dart';
import 'package:farm_tpf/utils/const_string.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:farm_tpf/utils/formatter.dart';

import 'bloc/plot_parameter_bloc.dart';

class PlotParameterScreen extends StatefulWidget {
  final int cropId;
  final bool isShowAppbar;
  PlotParameterScreen({required this.cropId, this.isShowAppbar = false});
  @override
  _PlotParameterScreenState createState() => _PlotParameterScreenState();
}

class _PlotParameterScreenState extends State<PlotParameterScreen> with AutomaticKeepAliveClientMixin {
  var plotParameterBloc = PlotParameterBloc(repository: Repository());
  final _scrollController = ScrollController();
  final _scrollThreshold = 250.0;
  @override
  void initState() {
    _scrollController.addListener(() {
      final maxScroll = _scrollController.position.maxScrollExtent;
      final currentScroll = _scrollController.position.pixels;
      if (maxScroll - currentScroll < _scrollThreshold) {
        plotParameterBloc.add(DataFetched(cropId: widget.cropId));
      }
    });
    plotParameterBloc.add(DataFetched(cropId: widget.cropId));
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: appbar(widget.isShowAppbar),
      body: SafeArea(
        child: Column(
          children: <Widget>[
            Expanded(
                child: BlocBuilder<PlotParameterBloc, PlotParameterState>(
              bloc: plotParameterBloc,
              builder: (context, state) {
                if (state is PlotParameterFailure) {
                  return Center(child: Text(state.errorString));
                }
                if (state is PlotParameterSuccess) {
                  if (state.items.isEmpty) {
                    return const Center(child: Text(label_list_empty));
                  }
                  return RefreshIndicator(
                      child: GridView.builder(
                        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2, childAspectRatio: 3 / 2),
                        physics: const AlwaysScrollableScrollPhysics(),
                        itemBuilder: (BuildContext context, int index) {
                          return index >= state.items.length ? BottomLoader() : ItemInfinityWidget(item: state.items[index]);
                        },
                        itemCount: state.hasReachedMax ? state.items.length : state.items.length + 1,
                        controller: _scrollController,
                      ),
                      onRefresh: () async {
                        plotParameterBloc.add(OnRefresh(cropId: widget.cropId));
                      });
                }
                return Center(
                  child: LoadingListPage(),
                );
              },
            ))
          ],
        ),
      ),
    );
  }

  PreferredSizeWidget? appbar(bool isShowAppbar) {
    if (isShowAppbar) {
      return AppBarWidget();
    }
  }

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

  @override
  bool get wantKeepAlive => true;
}

class ItemInfinityWidget extends StatelessWidget {
  final EnvironmentParameter item;

  const ItemInfinityWidget({Key? key, required this.item}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.all(8),
      decoration: BoxDecoration(
          color: Colors.white,
          border: Border.all(color: Colors.grey, width: 0.35),
          borderRadius: BorderRadius.circular(8),
          boxShadow: [BoxShadow(color: Colors.grey, blurRadius: 4, offset: const Offset(0, 3))]),
      padding: const EdgeInsets.all(8),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            item.index?.formatNumtoStringDecimal() ?? '',
            style: TextStyle(color: (item.status ?? false) ? Colors.red : AppColors.YELLOW, fontWeight: FontWeight.bold, fontSize: 22),
          ),
          Flexible(
            child: Text(
              "${item.name ?? ''}",
              maxLines: 2,
              style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 18),
            ),
          ),
          Text(item.executeDate?.format_DDMMYY_HHmm() ?? '', style: const TextStyle(fontSize: 13, color: Colors.grey))
        ],
      ),
    );
  }
}
