import 'package:farm_tpf/custom_model/CropPlot.dart';
import 'package:farm_tpf/data/repository/repository.dart';
import 'package:farm_tpf/presentation/custom_widgets/bloc/widget_row_plot_info.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/actions/environment_update/sc_edit_action_environment_update.dart';
import 'package:farm_tpf/presentation/screens/actions/sc_action.dart';
import 'package:farm_tpf/utils/const_color.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:get/get.dart';
import 'package:farm_tpf/utils/formatter.dart';

import 'bloc/plot_detail_bloc.dart';

class PlotHistoryScreen extends StatefulWidget {
  int? cropId;
  String? cropCode;
  int? cropType;
  PlotHistoryScreen({this.cropId, this.cropCode, this.cropType});
  @override
  _PlotHistoryScreenState createState() => _PlotHistoryScreenState();
}

class _PlotHistoryScreenState extends State<PlotHistoryScreen> with AutomaticKeepAliveClientMixin {
  @override
  void initState() {
    super.initState();
  }

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

  @override
  Widget build(BuildContext context) {
    return InfinityView(
      cropId: widget.cropId,
      cropCode: widget.cropCode,
    );
  }

  @override
  bool get wantKeepAlive => true;
}

class InfinityView extends StatefulWidget {
  int? cropId;
  String? cropCode;
  InfinityView({this.cropId, this.cropCode});
  @override
  _InfinityViewState createState() => _InfinityViewState();
}

class _InfinityViewState extends State<InfinityView> {
  var plotDetailBloc = PlotDetailBloc(repository: Repository());
  final _scrollController = ScrollController();
  final _scrollThreshold = 250.0;

  @override
  void initState() {
    plotDetailBloc.add(
      DataFetched(
        cropId: widget.cropId ?? -1,
        cropCode: widget.cropCode ?? '',
      ),
    );
    _scrollController.addListener(() {
      final maxScroll = _scrollController.position.maxScrollExtent;
      final currentScroll = _scrollController.position.pixels;
      if (maxScroll - currentScroll < _scrollThreshold) {
        plotDetailBloc.add(
          DataFetched(cropId: widget.cropId ?? -1, cropCode: widget.cropCode ?? ''),
        );
      }
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<PlotDetailBloc, PlotDetailState>(
      bloc: plotDetailBloc,
      builder: (context, state) {
        if (state is PlotDetailFailure) {
          return Center(child: Text(state.errorString));
        }
        if (state is PlotDetailSuccess) {
          if ((state.items ?? []).isEmpty) {
            return Center(
                child: Column(
              mainAxisSize: MainAxisSize.max,
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text("Không có dữ liệu lịch sử canh tác"),
                TextButton(
                  onPressed: () {
                    plotDetailBloc.add(
                      OnRefresh(cropId: widget.cropId ?? -1, cropCode: widget.cropCode ?? ''),
                    );
                  },
                  child: Text('Tải lại'),
                )
              ],
            ));
          }
          List<Activities> currentItems = List<Activities>.from(state.items ?? []);
          return SafeArea(
            child: Scaffold(
              body: RefreshIndicator(
                  child: ListView.builder(
                    padding: EdgeInsets.all(8),
                    physics: AlwaysScrollableScrollPhysics(),
                    itemBuilder: (BuildContext context, int index) {
                      return index >= (state.items ?? []).length
                          ? BottomLoader()
                          : ItemInfinityWidget(
                              currentItems: currentItems,
                              item: state.items?[index],
                              index: index,
                              currentPage: state.page ?? 0,
                              currentReachedMax: state.hasReachedMax ?? false,
                            );
                    },
                    itemCount: (state.hasReachedMax ?? false) ? (state.items ?? []).length : (state.items ?? []).length + 1,
                    controller: _scrollController,
                  ),
                  onRefresh: () async {
                    plotDetailBloc.add(
                      OnRefresh(cropId: widget.cropId ?? -1, cropCode: widget.cropCode ?? ''),
                    );
                  }),
            ),
          );
        }
        return Center(
          child: LoadingListPage(),
        );
      },
    );
  }

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

class ItemInfinityWidget extends StatelessWidget {
  final List<Activities> currentItems;
  final Activities item;
  final int currentPage;
  final bool currentReachedMax;
  final int index;

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

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
        child: WidgetRowPlotInfo(
            color: index % 2 == 0 ? AppColors.DEFAULT.withOpacity(0.3) : AppColors.DEFAULT.withOpacity(0.1),
            name: '${item.activityTypeDescription ?? ''}',
            value: item.executeDate?.format_DDMMYY_HHmm() ?? ''),
        onTap: () {
          if (item.activityTypeName == 'ACTIVE_TYPE_UPDATE_ENV') {
            Get.to(EditActionEnvironmentUpdate(
              cropId: item.cropId ?? -1,
              activityId: item.id,
              isEdit: true,
            ));
          } else {
            Get.to(ActionScreen(
              isEdit: true,
              cropId: item.cropId ?? -1,
              activityId: item.id ?? -1,
              activityType: item.activityTypeName ?? '',
              title: 'ActionScreen',
              idAction: item.activityTypeId ?? -1,
            ));
          }
        });
  }
}

class ActionType {
  Widget? listScreen;
  String? actionName;
  ActionType(String actionName, Widget listScreen) {
    this.actionName = actionName;
    this.listScreen = listScreen;
  }
}
