import 'dart:async';

import 'package:fis_i18n/i18n.dart';
import 'package:fis_ui/base_define/page.dart';
import 'package:fis_theme/theme.dart';
import 'package:fis_ui/index.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/router/router.dart';
import 'package:fis_ui/values/spacings.dart';
import 'package:flyinsono/pages/remedical/consultation/widgets/muti_select.dart';
import 'package:get/get.dart';

class FMutiSelectDialog<T> extends FStatefulWidget implements FPage {
  final List<T> selectedItems;
  final Future<List<T>> Function(String, int) loadMoreItems;
  final void Function(List<T>) onSubmit;
  final void Function(bool) onSelectedAllChanged;
  final FWidget Function(T) buildItem;
  final String? title;
  final int length;
  final bool isSelectedAll;

  FMutiSelectDialog({
    required this.selectedItems,
    required this.loadMoreItems,
    required this.onSubmit,
    required this.buildItem,
    required this.length,
    required this.onSelectedAllChanged,
    this.isSelectedAll = true,
    this.title,
  });

  @override
  FState<FStatefulWidget> createState() {
    return FMutiSelectState<T>();
  }

  @override
  String get pageName => 'FMutiSelectDialog';
}

class FMutiSelectState<T> extends FState<FMutiSelectDialog<T>> {
  final _searchController = TextEditingController();
  final _scrollController = ScrollController();
  int _index = 1;
  List<T> _selectedItems = [];
  List<T> _items = [];
  bool _isSelectedAll = true;
  Timer? timer;

  @override
  void initState() {
    super.initState();
    if (widget.isSelectedAll) {
      _isSelectedAll = true;
    } else {
      _isSelectedAll = false;
    }

    widget.loadMoreItems.call('', _index).then((items) {
      setState(() {
        _items.addAll(items);
      });
      if (_isSelectedAll) {
        setState(() {
          _selectedItems.addAll(items);
        });
      } else {
        setState(() {
          _selectedItems.addAll(widget.selectedItems);
        });
      }
    });
    _scrollController.addListener(_scrollListen);
  }

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

  @override
  FWidget build(BuildContext context) {
    return FSimpleDialog(
      okString: i18nBook.common.confirm.t,
      cancelString: i18nBook.common.cancel.t,
      isDefault: true,
      title: FText(
        widget.title ?? i18nBook.user.OrganizationLocated.t,
        style: TextStyle(color: Colors.white),
      ),
      onCancel: router.back,
      onClose: router.back,
      onOk: () {
        widget.onSelectedAllChanged.call(_isSelectedAll);
        widget.onSubmit.call(_selectedItems);
        router.back();
      },
      children: [
        FContainer(
          width: 600,
          height: 600,
          child: FColumn(
            children: [
              const FSizedBox(height: 5),
              _buildSerarchInput(),
              const FSizedBox(height: 10),
              _buildSelectAllLine(),
              const FSizedBox(height: 5),
              _buildItems(),
            ],
          ),
        )
      ],
    );
  }

  ///搜索框
  FWidget _buildSerarchInput() {
    return FContainer(
      padding: EdgeInsets.all(15),
      child: FRow(
        children: [
          FBorderInput(
            hintSize: 16,
            contentSize: 16,
            controller: _searchController,
            maxLength: 20,
            borderColor: Color.fromRGBO(234, 234, 234, 1),
            suffixIcon: FMaterial(
              color: Colors.transparent,
              child: FIconButton(
                name: "search",
                businessParent: this.widget,
                onPressed: () {},
                icon: FIcon(
                  Icons.search,
                ),
              ),
            ),
            height: 38,
            onChanged: (value) {
              timer?.cancel();
              timer = Timer(
                Duration(milliseconds: 300),
                () async {
                  _index = 1;
                  if (value.toString().isEmpty) {
                    _items.clear();
                    var items = await widget.loadMoreItems(
                        _searchController.text, _index);
                    setState(() {
                      _items = items;
                    });
                    return;
                  }
                  var items = await widget.loadMoreItems(
                      _searchController.text, _index);
                  setState(() {
                    _items = items;
                  });
                },
              );
            },
          ),
        ],
      ),
    );
  }

  FWidget _buildItems() {
    return FContainer(
      height: 450,
      child: FListView(
        shrinkWrap: true,
        controller: _scrollController,
        children: _items.map((e) {
          bool isSelected = _selectedItems.any((element) {
            if (element is FMutiSelectModel && e is FMutiSelectModel) {
              return element.code == e.code;
            }
            return false;
          });

          return FInkWell(
            onTap: () {
              if (_isSelectedAll) {
                setState(() {
                  _isSelectedAll = false;
                });
              }
              var item = _selectedItems.firstWhereOrNull((element) {
                if (element is FMutiSelectModel && e is FMutiSelectModel) {
                  return element.code == e.code;
                }
                return false;
              });
              bool _isSelected = item != null;
              print('_isSelected:$_isSelected');
              if (_isSelected) {
                setState(() {
                  _selectedItems.remove(item);
                });
              } else {
                setState(() {
                  _selectedItems.add(e);
                });
              }
              if (_selectedItems.length == _items.length) {
                _isSelectedAll = true;
              }
            },
            child: FContainer(
              height: 40,
              padding: EdgeInsets.symmetric(
                horizontal: 15,
                vertical: 8,
              ),
              child: FRow(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  widget.buildItem(e),
                  if (isSelected) ...[
                    FIcon(
                      Icons.done_rounded,
                      size: 20,
                      color: FTheme.ins.colorScheme.primary,
                    )
                  ],
                ],
              ),
            ),
          );
        }).toList(),
      ),
    );
  }

  FWidget _buildSelectAllLine() {
    return FRow(
      children: [
        const FSizedBox(width: FSpacings.XL),
        FText(i18nBook.common.ofTerm.translate([widget.length.toString()])),
        const FSizedBox(width: FSpacings.MINI_BUTTON),
        QuickFWidget(
          Checkbox(
            onChanged: (bool? value) {
              setState(() {
                _isSelectedAll = !_isSelectedAll;
              });

              if (_isSelectedAll) {
                _selectedItems.clear();
                setState(() {
                  _selectedItems.addAll(_items);
                });
              } else {
                setState(() {
                  _selectedItems.clear();
                });
              }
            },
            value: _isSelectedAll,
          ),
        ),
      ],
    );
  }

  Future<void> _scrollListen() async {
    if (_scrollController.position.pixels ==
        _scrollController.position.maxScrollExtent) {
      _index++;
      var newItems =
          await widget.loadMoreItems.call(_searchController.text, _index);
      setState(() {
        _items.addAll(newItems);
      });
      if (_isSelectedAll) {
        setState(() {
          _selectedItems.addAll(newItems);
        });
      }
    }
  }
}
