import 'package:farm_tpf/presentation/custom_widgets/button/second_button.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:multi_select_flutter/multi_select_flutter.dart';

import '../../../models/item_dropdown.dart';
import '../../../themes/app_colors.dart';
import '../../../themes/styles_text.dart';
import '../button/button_2_icon.dart';

class MultipleSelectBottomSheet extends StatefulWidget {
  final List<ItemDropDown>? initValue;
  final List<ItemDropDown> dataSources;
  final Function(List<ItemDropDown>) onSelected;
  final Color? borderColor;
  final String hint;
  final double? height;
  final String? errorText;
  final bool isDisable;
  final EdgeInsetsGeometry? contentPadding;
  final Color? disabledColor;

  const MultipleSelectBottomSheet({
    Key? key,
    required this.dataSources,
    required this.onSelected,
    required this.hint,
    this.initValue,
    this.borderColor,
    this.height,
    this.errorText,
    this.isDisable = false,
    this.contentPadding,
    this.disabledColor,
  }) : super(key: key);

  @override
  _MultipleSelectBottomSheetState createState() => _MultipleSelectBottomSheetState();
}

class _MultipleSelectBottomSheetState extends State<MultipleSelectBottomSheet> {
  var dataSources = ValueNotifier(<ItemDropDown>[]);
  var selectValue = ValueNotifier(<ItemDropDown>[]);
  FixedExtentScrollController? scrollController;
  var items = <MultiSelectItem<ItemDropDown>>[];
  final _searchCtl = TextEditingController();

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

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

  @override
  Widget build(BuildContext context) {
    items = widget.dataSources.map((e) => MultiSelectItem(e, e.value ?? '')).toList();
    selectValue.value = widget.initValue ?? <ItemDropDown>[];

    return ValueListenableBuilder<List<ItemDropDown>>(
      valueListenable: selectValue,
      builder: (context, selecteds, _) {
        return Button2Icon(
          leftIcon: CupertinoIcons.slider_horizontal_3,
          title: widget.hint,
          rightWidget: Container(
            width: 16,
            height: 16,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(12),
              color: Colors.blue,
            ),
            child: Center(
              child: Text(
                '${selecteds.length}',
                style: TextStyle(fontSize: 10, color: Colors.white),
              ),
            ),
          ),
          onPressed: () {
            FocusScope.of(context).requestFocus(FocusNode());
            _showMultiSelect(context);
          },
        );
      },
    );
  }

  void _showMultiSelect(BuildContext context) async {
    var selectedIds = selectValue.value.map((e) => e.key).toList();
    var selecteds = ValueNotifier(
      items
          .where((element) => selectedIds.contains(element.value.key))
          .map(
            (e) => e.value,
          )
          .toList(),
    );
    // var selectValue = ValueNotifier(<ItemDropDown>[]);

    _searchCtl.clear();
    dataSources.value = List.of(widget.dataSources);
    return showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          contentPadding: const EdgeInsets.all(8),
          content: Container(
            width: double.maxFinite,
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                _buildSelectAll(selecteds),
                Expanded(
                  child: ValueListenableBuilder<List<ItemDropDown>>(
                    valueListenable: dataSources,
                    builder: (context, sources, _) {
                      return ValueListenableBuilder<List<ItemDropDown>>(
                          valueListenable: selecteds,
                          builder: (context, valueSelected, _) {
                            return ListView.builder(
                              shrinkWrap: true,
                              itemBuilder: ((context, index) {
                                var item = sources[index];
                                var isSelected = valueSelected.map((e) => e.key ?? '').contains(item.key);
                                return InkWell(
                                  onTap: () {
                                    if (!isSelected) {
                                      selecteds.value.add(item);
                                      selecteds.notifyListeners();
                                    } else {
                                      selecteds.value.removeWhere((element) => element.key == item.key);
                                      selecteds.notifyListeners();
                                    }
                                  },
                                  child: Row(
                                    children: [
                                      Checkbox(
                                        value: isSelected,
                                        onChanged: (val) {
                                          if (val == true) {
                                            selecteds.value.add(item);
                                            selecteds.notifyListeners();
                                          } else {
                                            selecteds.value.removeWhere((element) => element.key == item.key);
                                            selecteds.notifyListeners();
                                          }
                                        },
                                      ),
                                      Expanded(
                                        child: Text(
                                          item.value ?? '',
                                          style: StylesText.body6,
                                        ),
                                      ),
                                    ],
                                  ),
                                );
                              }),
                              itemCount: sources.length,
                            );
                          });
                    },
                  ),
                ),
                Row(
                  children: [
                    Expanded(
                      child: SecondButton(
                        title: 'Huỷ',
                        color: AppColors.neutral3,
                        onPressed: () {
                          Get.back();
                        },
                      ),
                    ),
                    const SizedBox(
                      width: 16,
                    ),
                    Expanded(
                      child: SecondButton(
                        title: 'Chọn',
                        color: AppColors.primary1,
                        onPressed: () {
                          Get.back();
                          selectValue.value = selecteds.value;
                          widget.onSelected(selectValue.value);
                        },
                      ),
                    ),
                  ],
                )
              ],
            ),
          ),
        );
      },
    );
  }

  Widget _buildSelectAll(ValueNotifier<List<ItemDropDown>> selecteds) {
    return ValueListenableBuilder<List<ItemDropDown>>(
      valueListenable: dataSources,
      builder: (context, sources, _) {
        return ValueListenableBuilder<List<ItemDropDown>>(
          valueListenable: selecteds,
          builder: (context, valueSelected, _) {
            final isSelectAll = valueSelected.where((e) => sources.any((t) => t.key == e.key)).length == sources.length && sources.isNotEmpty;
            final tristate = valueSelected.where((e) => sources.firstWhereOrNull((t) => t.key == e.key) != null).isNotEmpty;
            return Visibility(
              visible: sources.isNotEmpty,
              child: Container(
                decoration: BoxDecoration(
                  border: Border(
                    bottom: BorderSide(
                      color: AppColors.neutral1,
                      width: 0.5,
                    ),
                  ),
                ),
                child: InkWell(
                  onTap: () {
                    if (isSelectAll) {
                      selecteds.value = List.of(valueSelected)..removeWhere((e) => sources.firstWhereOrNull((t) => t.key == e.key) != null);
                    } else {
                      final itemsAdded = List.of(sources)..removeWhere((e) => valueSelected.firstWhereOrNull((t) => t.key == e.key) != null);
                      selecteds.value = [...valueSelected, ...itemsAdded];
                    }
                  },
                  child: Row(
                    children: [
                      Checkbox(
                        value: isSelectAll ? isSelectAll : (tristate ? null : tristate),
                        tristate: true,
                        onChanged: (val) {
                          if (isSelectAll) {
                            selecteds.value = List.of(valueSelected)..removeWhere((e) => sources.firstWhereOrNull((t) => t.key == e.key) != null);
                          } else {
                            final itemsAdded = List.of(sources)..removeWhere((e) => valueSelected.firstWhereOrNull((t) => t.key == e.key) != null);
                            selecteds.value = [...valueSelected, ...itemsAdded];
                          }
                        },
                      ),
                      Text(
                        'Tất cả',
                        style: StylesText.body6,
                      ),
                    ],
                  ),
                ),
              ),
            );
          },
        );
      },
    );
  }
}
