// ignore_for_file: public_member_api_docs, sort_constructors_first
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:get/get.dart';

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/crop_status/sc_edit_action_crop_status.dart';
import 'package:farm_tpf/presentation/screens/actions/disease/sc_edit_action_disease.dart';
import 'package:farm_tpf/presentation/screens/actions/dung/sc_edit_action_dung.dart';
import 'package:farm_tpf/presentation/screens/actions/end/sc_edit_action_end.dart';
import 'package:farm_tpf/presentation/screens/actions/environment_update/sc_edit_action_environment_update.dart';
import 'package:farm_tpf/presentation/screens/actions/harvest/sc_edit_action_harvest.dart';
import 'package:farm_tpf/presentation/screens/actions/harvest_process/sc_edit_action_harvest_process.dart';
import 'package:farm_tpf/presentation/screens/actions/nursery/sc_edit_action_nursery.dart';
import 'package:farm_tpf/presentation/screens/actions/other/sc_edit_action_other.dart';
import 'package:farm_tpf/presentation/screens/actions/packing/sc_edit_action_packing.dart';
import 'package:farm_tpf/presentation/screens/actions/plant/sc_edit_action_plant.dart';
import 'package:farm_tpf/presentation/screens/actions/sell/sc_edit_action_sell.dart';
import 'package:farm_tpf/presentation/screens/actions/spraying/sc_edit_action_spraying.dart';
import 'package:farm_tpf/presentation/screens/actions/use_water/sc_edit_action_user_water.dart';
import 'package:farm_tpf/utils/const_color.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 ?? -1,
      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: [
                const Text("Không có dữ liệu lịch sử canh tác"),
                InkWell(
                  onTap: () {
                    plotDetailBloc.add(OnRefresh(cropId: widget.cropId ?? -1, cropCode: widget.cropCode ?? ''));
                  },
                  child: const Text('Tải lại'),
                ),
              ],
            ));
          }
          var currentItems = List<Activities>.from(state.items);
          return SafeArea(
            child: Scaffold(
              body: RefreshIndicator(
                  child: ListView.builder(
                    padding: const EdgeInsets.all(8),
                    physics: const AlwaysScrollableScrollPhysics(),
                    itemBuilder: (BuildContext context, int index) {
                      return index >= state.items.length
                          ? BottomLoader()
                          : ItemInfinityWidget(
                              currentItems: currentItems,
                              item: state.items[index],
                              index: index,
                              currentPage: state.page,
                              currentReachedMax: state.hasReachedMax);
                    },
                    itemCount: state.hasReachedMax ? 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_NURSERY") {
            Get.to(EditActionNurseryScreen(
              cropId: item.cropId ?? -1,
              activityId: item.id,
              isEdit: true,
            ));
          } else if (item.activityTypeName == "ACTIVE_TYPE_STATUS_CROP") {
            Get.to(EditActionCropStatusScreen(
              cropId: item.cropId ?? -1,
              activityId: item.id,
              isEdit: true,
            ));
          } else if (item.activityTypeName == "ACTIVE_TYPE_UPDATE_ENV") {
            Get.to(EditActionEnvironmentUpdate(
              cropId: item.cropId ?? -1,
              activityId: item.id,
              isEdit: true,
            ));
          } else if (item.activityTypeName == "ACTIVE_TYPE_PESTS_INVESTIGATION") {
            Get.to(EditActionDiseaseScreen(
              cropId: item.cropId ?? -1,
              activityId: item.id,
              isEdit: true,
            ));
          } else if (item.activityTypeName == "ACTIVE_TYPE_USE_WATER") {
            Get.to(EditActionUseWaterScreen(
              cropId: item.cropId ?? -1,
              activityId: item.id,
              isEdit: true,
            ));
          } else if (item.activityTypeName == "ACTIVE_TYPE_HARVEST") {
            Get.to(EditActionHarvestScreen(
              cropId: item.cropId ?? -1,
              activityId: item.id,
              isEdit: true,
            ));
          } else if (item.activityTypeName == "ACTIVE_TYPE_PACKING") {
            Get.to(EditActionPackingScreen(
              cropId: item.cropId ?? -1,
              activityId: item.id,
              isEdit: true,
            ));
          } else if (item.activityTypeName == "ACTIVE_TYPE_SELL") {
            Get.to(EditActionSellScreen(
              cropId: item.cropId ?? -1,
              activityId: item.id,
              isEdit: true,
            ));
          } else if (item.activityTypeName == "ACTIVE_TYPE_END") {
            Get.to(EditActionEndScreen(
              cropId: item.cropId ?? -1,
              activityId: item.id,
              isEdit: true,
            ));
          } else if (item.activityTypeName == "ACTIVE_TYPE_STATUS_GROW") {
            Get.to(EditActionPlantScreen(
              cropId: item.cropId ?? -1,
              activityId: item.id,
              isEdit: true,
            ));
          } else if (item.activityTypeName == "ACTIVE_TYPE_MANURING") {
            Get.to(EditActionDungScreen(
              cropId: item.cropId ?? -1,
              activityId: item.id,
              isEdit: true,
            ));
          } else if (item.activityTypeName == "ACTIVE_TYPE_SPRAY") {
            Get.to(EditActionSprayingScreen(
              cropId: item.cropId ?? -1,
              activityId: item.id,
              isEdit: true,
            ));
          } else if (item.activityTypeName == "ACTIVE_TYPE_PROCESS") {
            Get.to(EditActionHarvestProcessScreen(
              cropId: item.cropId ?? -1,
              activityId: item.id,
              isEdit: true,
            ));
          } else {
            Get.to(EditActionOtherScreen(
              cropId: item.cropId ?? -1,
              activityId: item.id,
              isEdit: true,
            ));
          }
        });
  }
}

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