import 'package:fis_i18n/i18n.dart';
import 'package:fis_theme/theme.dart';
import 'package:fis_ui/base_define/page.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_ui/widgets/checkbox/rectangle_checkbox.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/router/router.dart';
import 'package:flyinsono/architecture/utils/prompt_box.dart';
import 'package:flyinsono/pages/remedical/report/report_edit/entitys/report_tag_key.dart';

class AddReportTag extends FStatefulWidget implements FPage {
  final Map<ReportTagKey, List<String>> allReportTags;
  final List<String> selectedTags;
  final void Function(List<String>) onPressed;
  @override
  final String pageName;

  AddReportTag(this.allReportTags, this.selectedTags, this.onPressed,
      {this.pageName = 'AddReportTag'});

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

class AddReportTagState extends FState<AddReportTag> {
  final Map<ReportTagKey, String> selectedLabes = {};
  final ScrollController _scrollController = ScrollController();
  final ScrollController _tagScrollController = ScrollController();
  List<String> _selectedTags = [];

  @override
  void initState() {
    _selectedTags.addAll(widget.selectedTags);
    super.initState();
  }

  @override
  void didUpdateWidget(AddReportTag oldWidget) {
    if (oldWidget.selectedTags != widget.selectedTags) {
      _selectedTags.clear();
      setState(() {
        _selectedTags.addAll(widget.selectedTags);
      });
    }
    super.didUpdateWidget(oldWidget);
  }

  @override
  FWidget build(BuildContext context) {
    return FSimpleDialog(
      title: FText(
        i18nBook.remedical.addReportTag.t,
        style: TextStyle(color: Colors.white, fontSize: 18),
      ),
      isDefault: true,
      okString: i18nBook.common.save.t,
      cancelString: i18nBook.common.cancel.t,
      onOk: () {
        widget.onPressed.call(_selectedTags);
      },
      onCancel: () {
        router.back();
      },
      onClose: () {
        router.back();
      },
      contentPadding: EdgeInsets.symmetric(vertical: 20, horizontal: 20),
      children: [
        _buildAddReportTagContent(context),
      ],
    );
  }

  ///添加标签内部视图
  FWidget _buildAddReportTagContent(BuildContext context) {
    return FContainer(
      width: 530,
      child: FColumn(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          FText(i18nBook.remedical.selectTags.t),
          const FSizedBox(height: 20),
          _buildLabelsSelect(context),
          const FSizedBox(height: 20),
          FText(i18nBook.remedical.addedTags.t),
          _buildSelectedTags(context),
          const FSizedBox(height: 20),
          //   _buildCheckNotRemeber(),
        ],
      ),
    );
  }

  ///标签选择
  FWidget _buildLabelsSelect(BuildContext context) {
    final selectTags = widget.allReportTags;
    var decoration = FBorderInput.buildDecoration(
      height: 38,
      contentSize: 16,
      hintSize: 16,
      hintText: i18nBook.remedical.searchOrSelectTags.t,
      borderColor: Colors.grey[350],
    );
    return FContainer(
      height: selectTags.length * 60,
      child: FAlwaysScrollListView(
        scrollController: _scrollController,
        child: QuickFWidget(ScrollConfiguration(
          behavior: ScrollConfiguration.of(context).copyWith(scrollbars: false),
          child: FListView.builder(
            controller: _scrollController,
            itemCount: selectTags.length,
            itemBuilder: (BuildContext context, int index) {
              final tagKey = selectTags.keys.toList()[index];
              final tagValues = selectTags[tagKey] ?? [];
              final labelInputController = TextEditingController();
              return FContainer(
                margin: EdgeInsets.symmetric(vertical: 10),
                child: FRow(
                  children: [
                    FContainer(
                      width: 110,
                      child: FText(tagKey.name),
                    ),
                    const FSizedBox(width: 10),
                    FContainer(
                      width: 310,
                      child: FSuggesionInput<String>(
                        inputFieldConfiguration:
                            FSuggesionInputFieldConfiguration(
                          decoration: decoration.copyWith(
                            suffixIcon: FContainer(
                              height: 36,
                              padding:
                                  EdgeInsets.only(bottom: 10, top: 0, right: 4),
                              child: FIconButton(
                                name: "delete",
                                businessParent: widget,
                                icon: FIcon(
                                  Icons.close,
                                  size: 20,
                                ),
                                onPressed: () {
                                  selectedLabes[tagKey] = '';
                                  labelInputController.text = '';
                                },
                              ),
                            ),
                          ),
                          style: TextStyle(fontSize: 16),
                          maxLength: 100,
                          onChanged: (val) {
                            selectedLabes[tagKey] = val;
                          },
                          controller: labelInputController,
                        ),
                        optionItemBuilder: (_, data) {
                          return FListTile(
                            title: FText(
                              data,
                              style: const TextStyle(
                                color: Colors.grey,
                                fontSize: FInput.hintSize,
                              ),
                            ),
                          );
                        },
                        optionItemsFetcher: (pattern) {
                          return tagValues
                              .where((element) => element.contains(pattern));
                        },
                        onOptionSelected: (data) {
                          labelInputController.text = data;
                          selectedLabes[tagKey] = data;
                        },
                        noItemsFoundText: i18nBook.remedical.notFoundTag.t,
                      ),
                    ),
                    const FSizedBox(width: 15),
                    FElevatedButton(
                      businessParent: widget,
                      name: "$tagKey",
                      child: FText(i18nBook.common.add.t),
                      onPressed: () {
                        final target = selectedLabes[tagKey] ?? '';
                        final selectedLabels = _selectedTags;
                        if (selectedLabels.contains(target)) {
                          PromptBox.toast(i18nBook.remedical.addedTags.t);
                        } else {
                          final reportTag = widget.allReportTags[tagKey] ?? [];
                          if (reportTag.contains(target)) {
                            _selectedTags.add(target);
                            labelInputController.text = '';
                          } else {
                            PromptBox.toast(i18nBook.remedical.canNotTag.t);
                          }
                        }
                        setState(() {});
                      },
                    ),
                  ],
                ),
              );
            },
          ),
        )),
      ),
    );
  }

  ///已选中的标签展示
  FWidget _buildSelectedTags(BuildContext context) {
    return FSizedBox(
      height: 130,
      child: FAlwaysScrollListView(
        scrollController: _tagScrollController,
        child: QuickFWidget(ScrollConfiguration(
          behavior: ScrollConfiguration.of(context).copyWith(scrollbars: false),
          child: FListView(
            controller: _tagScrollController,
            children: [
              FWrap(
                runAlignment: WrapAlignment.start,
                runSpacing: 5,
                spacing: 10,
                children: List.generate(
                  _selectedTags.length,
                  (index) => FContainer(
                    margin: EdgeInsets.only(top: 10),
                    decoration: new BoxDecoration(
                      borderRadius:
                          BorderRadius.all(Radius.circular(4.0)), //圆角弧度
                      border: new Border.all(
                        width: 1,
                        color: FTheme.ins.colorScheme.primary,
                      ),
                    ),
                    child: FRow(
                      mainAxisSize: MainAxisSize.min,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        FSizedBox(width: 5),
                        FContainer(
                          alignment: Alignment.center,
                          child: FText(
                            _selectedTags[index],
                            style: TextStyle(fontSize: 16),
                          ),
                        ),
                        const FSizedBox(width: 10),
                        FContainer(
                          alignment: Alignment.center,
                          child: FGestureDetector(
                            name: "remove:$index",
                            businessParent: widget,
                            onTap: () {
                              _selectedTags.removeAt(index);
                              setState(() {});
                            },
                            child: FIcon(
                              Icons.close,
                              color: FTheme.ins.colorScheme.primary,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ],
          ),
        )),
      ),
    );
  }

  ///是否再次提醒
  FWidget _buildCheckNotRemeber() {
    bool isRemeber = false;
    return FObx(
      () => FRow(
        children: [
          FRectangleCheckbox(
            value: isRemeber,
            isCheck: isRemeber,
          ),
          FSizedBox(width: 10),
          FMouseRegion(
            cursor: SystemMouseCursors.click,
            child: FGestureDetector(
              name: "isRemeber",
              businessParent: widget,
              onTap: () {
                isRemeber = !isRemeber;
              },
              child: FText(i18nBook.remedical.doNotRemind.t),
            ),
          )
        ],
      ),
    );
  }
}
