import 'package:farm_tpf/data/repository/repository.dart';
import 'package:farm_tpf/presentation/custom_widgets/button/button_2_icon.dart';
import 'package:farm_tpf/presentation/custom_widgets/button/second_button.dart';
import 'package:farm_tpf/presentation/screens/codes/code_detail_page.dart';
import 'package:farm_tpf/presentation/screens/codes/create_stamp_page.dart';
import 'package:farm_tpf/presentation/screens/codes/models/stamp.dart';
import 'package:farm_tpf/presentation/screens/codes/widgets/item_code.dart';
import 'package:farm_tpf/presentation/screens/task/models/task_update_request.dart';
import 'package:farm_tpf/themes/app_colors.dart';
import 'package:farm_tpf/utils/const_common.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:get/get.dart';

import '../../../models/item_dropdown.dart';
import '../../../themes/styles_text.dart';
import '../../../utils/const_string.dart';
import '../../../utils/helpers.dart';
import '../../custom_widgets/bottom_loader.dart';
import '../../custom_widgets/dropdown/multiple_select_bottom_sheet.dart';
import '../../custom_widgets/loading_list_page.dart';
import '../plot/widget_search.dart';
import 'bloc/task_bloc.dart';
import 'create_task_page.dart';
import 'task_detail_page.dart';
import 'widgets/task_item.dart';

class TaskPage extends StatefulWidget {
  final int cropId;
  const TaskPage({super.key, required this.cropId});

  @override
  State<TaskPage> createState() => _TaskPageState();
}

class _TaskPageState extends State<TaskPage> {
  final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
  TaskBloc bloc = TaskBloc(Repository());
  final _scrollController = ScrollController();
  final _scrollThreshold = 250.0;

  @override
  void initState() {
    bloc.cropId = widget.cropId;
    bloc.add(DataFetched());

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

  @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>[
            Row(
              children: [
                ValueListenableBuilder<String>(
                  valueListenable: bloc.sort,
                  builder: (context, sort, _) {
                    return Button2Icon(
                      leftIcon: (sort == describeEnum(SortType.asc)) ? CupertinoIcons.arrow_up : CupertinoIcons.arrow_down,
                      title: 'Hoàn thành',
                      onPressed: () {
                        if (sort == describeEnum(SortType.asc)) {
                          bloc.sort.value = describeEnum(SortType.desc);
                        } else {
                          bloc.sort.value = describeEnum(SortType.asc);
                        }
                        bloc.sort.notifyListeners();
                        bloc.add(OnRefresh());
                      },
                    );
                  },
                ),
                ValueListenableBuilder<List<ItemDropDown>>(
                  valueListenable: bloc.selectedStatus,
                  builder: (context, selecteds, _) {
                    return ValueListenableBuilder<List<ItemDropDown>>(
                      valueListenable: bloc.status,
                      builder: (context, status, _) {
                        return MultipleSelectBottomSheet(
                          dataSources: status,
                          initValue: selecteds,
                          onSelected: (val) {
                            bloc.selectedStatus.value = val;
                            Helpers.hideKeyboard(context);
                            bloc.add(OnRefresh());
                          },
                          hint: 'Trạng thái',
                        );
                      },
                    );
                  },
                ),
                const Spacer(),
                SecondButton(
                  onPressed: () {
                    Get.to(() => CreateTaskPage(
                          cropId: widget.cropId,
                        ))?.then((value) {
                      if (value != null) {
                        bloc.add(OnRefresh());
                      }
                    });
                  },
                  title: 'Thêm',
                  leftIcon: CupertinoIcons.add,
                  color: AppColors.primary1,
                  textColor: Colors.white,
                  borderColor: AppColors.primary1,
                ),
              ],
            ),
            const SizedBox(
              height: 4,
            ),
            Expanded(
              child: mainBody(),
            ),
          ],
        ),
      ),
    );
  }

  Widget mainBody() {
    return BlocBuilder<TaskBloc, TaskState>(
      bloc: bloc,
      builder: (context, state) {
        if (state is TaskFailure) {
          return Center(child: Text(state.errorString));
        }
        if (state is TaskSuccess) {
          if ((state.items ?? []).isEmpty) {
            return Center(child: Text(label_list_empty));
          }
          return RefreshIndicator(
              child: ListView.builder(
                physics: AlwaysScrollableScrollPhysics(),
                itemBuilder: (BuildContext context, int index) {
                  print('index: $index');
                  print('state.items: ${state.items?.length}');
                  return index >= (state.items ?? []).length
                      ? BottomLoader()
                      : ItemTask(
                          item: state.items?[index],
                          onPressed: () {
                            Get.to(
                              () => TaskDetailPage(
                                taskId: state.items?[index].id,
                              ),
                            )?.then((value) {
                              if (value != null) {
                                bloc.add(OnRefresh());
                              }
                            });
                          },
                          onChangedStatus: (status) {
                            bloc.updateStatusTask(
                              RequestTaskUpdate(
                                id: state.items?[index].id,
                                completed: status,
                              ),
                              onSuccess: () {
                                bloc.add(OnRefresh());
                              },
                            );
                          },
                        );
                },
                itemCount: (state.hasReachedMax ?? false) ? (state.items ?? []).length : (state.items ?? []).length + 1,
                controller: _scrollController,
              ),
              onRefresh: () async {
                bloc.add(OnRefresh());
              });
        }
        return Center(
          child: LoadingListPage(),
        );
      },
    );
  }
}
