import 'package:fis_i18n/i18n.dart';
import 'package:fis_theme/theme.dart';
import 'package:fis_ui/index.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/router/index.dart';
import 'package:flyinsono/managers/interfaces/appointment_consultation.dart';
import 'package:flyinsono/views/mobile/confirm_application_page/widgets/multi_select_popup.dart';
import 'package:flyinsono/views/mobile/confirm_application_page/widgets/single_select_popup.dart';
import 'package:flyinsono/views/mobile/confirm_application_page/widgets/special_multi_select_popup.dart';
import 'package:get/get.dart';

/// 手机端选择器
class FSelectSheet<T, TValue> extends FStatefulWidget {
  /// 数据源
  final List<T> source;

  ///图标
  final FWidget? icon;

  ///尾部图标
  final FWidget? suffixIcon;

  ///提示文字
  final String? hintText;

  ///点击事件
  final Function? onClick;

  ///值
  final TValue? value;

  /// 多选框的值
  final List<int>? valueList;

  /// 特殊多选框的值 不能仅仅通过下标判断
  final List<String>? specialValueList;

  final List<String>? specialValueNameList;

  /// 选项值提取器
  ///
  /// [data] 选项数据源
  final TValue Function(T data) optionValueExtractor;

  /// 选项文本提取器
  ///
  /// [data] 选项数据源
  final String Function(T data) optionLabelExtractor;

  ///边框文字
  final String? borderText;

  /// 下拉选中的值
  final ValueCallback? onChange;

  /// 下拉选中的值
  final ValueCallback? onChangeString;

  /// 是否多选
  final bool? isMultiSelect;

  /// 多选最多人数
  final int? maxMembers;

  /// 未选择的时候提示
  final String? tipTitle;

  /// 当前数据为空的提示
  final String? inkWellTitle;

  /// 是否特殊ui
  final bool? isSpecial;

  /// 弹出框的高度
  final double? height;

  FSelectSheet({
    Key? key,
    this.icon,
    this.onClick,
    this.hintText,
    this.value,
    this.valueList,
    this.specialValueList,
    this.specialValueNameList,
    this.borderText = '',
    this.suffixIcon,
    required this.source,
    required this.optionValueExtractor,
    required this.optionLabelExtractor,
    this.onChange,
    this.onChangeString,
    this.isMultiSelect = true,
    this.isSpecial = false,
    this.tipTitle = '',
    this.inkWellTitle = '',
    this.maxMembers,
    this.height,
  }) : super(key: key);

  @override
  FState<FSelectSheet<T, TValue>> createState() =>
      _FSelectSheetState<T, TValue>();
}

class FSelectSheetModel<T> {
  final T value;

  final String title;

  FSelectSheetModel({
    required this.value,
    required this.title,
  });
  static generateList(int count) {
    return List.generate(
      count,
      (index) => FSelectSheetModel(value: index, title: "User_$index"),
    );
  }
}

class _FSelectSheetState<T, TValue> extends FState<FSelectSheet<T, TValue>> {
  List<int> indexList = [];

  List<String> specialList = [];

  List<String> specialString = [];

  int index = 0;
  @override
  FWidget build(BuildContext context) {
    return FInkWell(
      onTap: () {
        showModalBottomSheet(
          isDismissible: false,
          isScrollControlled: widget.height != null ? true : false,
          builder: (BuildContext context) {
            return FContainer(
              padding: widget.height != null
                  ? EdgeInsets.symmetric(horizontal: 50)
                  : EdgeInsets.zero,
              child: FColumn(
                children: [
                  FContainer(
                    decoration: BoxDecoration(
                      border: Border(
                        bottom: BorderSide(
                          color: Color.fromRGBO(211, 211, 211, 0.3),
                        ),
                        left: widget.height != null
                            ? BorderSide(
                                color: Color.fromRGBO(211, 211, 211, 0.3),
                              )
                            : BorderSide.none,
                        right: widget.height != null
                            ? BorderSide(
                                color: Color.fromRGBO(211, 211, 211, 0.3),
                              )
                            : BorderSide.none,
                      ),
                    ),
                    child: FRow(
                      mainAxisSize: MainAxisSize.max,
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        _buildConfirmOrCancelInkWell(
                          title: i18nBook.common.cancel.t,
                          onTap: () {
                            Get.find<IAppointmentConsultation>()
                                .onCancelAddedParticipant
                                .emit(
                                  this,
                                  true,
                                );
                            _onChangeSelectValue();
                            router.back();
                          },
                        ),
                        _buildConfirmOrCancelInkWell(
                          title: i18nBook.common.confirm.t,
                          onTap: () {
                            _onChangeSelectValue();

                            Navigator.of(context).pop();
                          },
                          textColor: FTheme.ins.colorScheme.primary,
                        ),
                      ],
                    ),
                  ),
                  FExpanded(
                    child: _buildBodyContent(),
                  ),
                ],
              ),
            );
          },
          context: context,
        );
      },
      child: FContainer(
        padding: EdgeInsets.symmetric(
          vertical: 15,
        ),
        child: FRow(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            FExpanded(child: _buildTextContent()),
            widget.suffixIcon ??
                FIcon(
                  Icons.chevron_right,
                  color: Color.fromRGBO(164, 164, 164, 1),
                ),
          ],
        ),
      ),
    );
  }

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

  @override
  void initState() {
    super.initState();
    specialList = widget.specialValueList ?? [];
    specialString = widget.specialValueNameList ?? [];
    indexList = widget.valueList ?? [];
  }

  FWidget _buildBodyContent() {
    if (widget.isSpecial!) {
      return FSpecialMultiSelectPopup(
        source: widget.source,
        value: widget.specialValueList,
        valueName: widget.specialValueNameList,
        maxMembers: widget.maxMembers,
        height: widget.height,
        onChangeIndex: (value) {
          specialList = value;
        },
        onChangeString: (value) {
          specialString = value;
        },
      );
    } else {
      if (widget.isMultiSelect!) {
        return FMultiSelectPopup(
          source: widget.source,
          value: widget.valueList,
          height: widget.height,
          onChangeIndex: (value) {
            indexList = value;
          },
        );
      }
      return FSigleSelectPopup(
        source: widget.source,
        value: widget.value,
        height: widget.height,
        onChangeIndex: (value) {
          index = value;
        },
      );
    }
  }

  FWidget _buildConfirmOrCancelInkWell({
    Color? textColor,
    required String title,
    required Function onTap,
  }) {
    return FInkWell(
      child: FContainer(
        padding: EdgeInsets.all(15),
        child: FText(
          title,
          style: TextStyle(
            color: textColor,
          ),
          textAlign: TextAlign.right,
          overflow: TextOverflow.ellipsis,
        ),
      ),
      onTap: () => onTap.call(),
    );
  }

  ///区域文本内容
  FWidget _buildTextContent() {
    if (widget.value == null || widget.value == '')
      return FText(
        widget.hintText!,
        style: TextStyle(
          fontSize: 14,
          color: Color.fromRGBO(155, 155, 155, 1),
        ),
        textAlign: TextAlign.right,
        overflow: TextOverflow.ellipsis,
      );
    else {
      /// 判断是否是多选项
      if (widget.isMultiSelect!) {
        return FText(
          widget.value.toString(),
          style: TextStyle(
            fontSize: 14,
            color: Colors.black,
          ),
          textAlign: TextAlign.right,
          overflow: TextOverflow.ellipsis,
          // maxLines: 1,
        );
      } else {
        /// 单选项
        return FText(
          widget.source.length == 0
              ? ''
              : widget.optionLabelExtractor(
                  widget.source[widget.source.indexWhere(
                    (element) =>
                        widget.optionValueExtractor(element) ==
                        widget.value.toString(),
                  )],
                ),
          style: TextStyle(
            fontSize: 14,
            color: Colors.black,
          ),
          textAlign: TextAlign.right,
          overflow: TextOverflow.ellipsis,
          maxLines: 1,
        );
      }
    }
  }

  /// 切换选择值
  void _onChangeSelectValue() {
    if (widget.isSpecial!) {
      widget.onChange?.call(specialList);
      widget.onChangeString?.call(specialString);
    } else {
      if (!widget.isMultiSelect!) {
        widget.onChange?.call(
          widget.optionValueExtractor(
            widget.source[index],
          ),
        );
      } else {
        if (indexList.length != 0) {
          widget.onChange?.call(indexList);
        }
      }
    }
  }
}
