import 'package:fis_i18n/i18n.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:fis_ui/base_define/page.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_ui/values/font_sizes.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/pages/index.dart';
import 'package:get/get.dart';

/// 词条库左侧卡片
///
/// [index] 词条库选中下标
/// [thesaurusInfo] 词条库内容
class EntryCard extends StatefulWidget implements FWidget {
  EntryCard({
    required this.index,
    this.thesaurusInfo,
  });

  final int index;
  final ThesaurusDTO? thesaurusInfo;
  @override
  State<StatefulWidget> createState() => _EntryCardState();
}

///词条库考状态组件
class _EntryCardState extends State<EntryCard> {
  bool hovering = false;
  @override
  FWidget build(BuildContext context) {
    return _BuildEntryCardContentView(
      widget.index,
      widget.thesaurusInfo,
    );
  }
}

///词条库布局
class _BuildEntryCardContentView extends FisView<VocabularyEntryController>
    implements FPage {
  final int index;
  final ThesaurusDTO? thesaurusInfo;
  late bool _isActive = false;

  @override
  final String pageName = '_BuildEntryCardContentView';

  _BuildEntryCardContentView(this.index, this.thesaurusInfo);

  @override
  FWidget build(BuildContext context) {
    final child = FObx(() {
      controller.state.activeEntryIndex;
      if (kIsMobile) {
        _isActive = false;
      } else {
        _isActive =
            controller.state.thesaurusCode == thesaurusInfo?.thesaurusCode;
      }
      return FStack(
        children: [
          SwipeCard(
            index: index,
            isActive: _isActive,
            child: FRow(
              children: [
                if (kIsMobile) ...[
                  _buildVacabularyIconContainer(),
                  const FSizedBox(width: 15),
                ],
                FColumn(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    FRow(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisSize: MainAxisSize.max,
                      children: [
                        if (!kIsMobile) ...[
                          _buildVacabularyIconContainer(),
                        ],
                        _buildVacabularySourceItem(),
                      ],
                    ),
                    if (!kIsMobile) ...[
                      _thesaurusUIPlaceHolder(),
                      _getOperationArea()
                    ],
                  ],
                ),
              ],
            ),
            onTap: () {
              controller.clickEntryCard(
                index,
                thesaurusInfo!,
              );
            },
          ),
        ],
      );
    });
    return child;
  }

  FWidget _buildVacabularyIconContainer() {
    return FContainer(
      padding: EdgeInsets.only(
        right: 15,
      ),
      child: FIcon(
        FIcons.vocabulary_entry,
        size: 50,
        color: _isActive ? Colors.white : Colors.black,
      ),
    );
  }

  FWidget _buildVacabularySourceItem() {
    return FContainer(
      width: 250,
      child: FColumn(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildThesaurusName(),
          FSizedBox(
            height: 6,
          ),
          FRow(
            children: [
              _buildThesaurusCreationTitle(),
              FSizedBox(
                width: 15,
              ),
              _buildThesaurusSourceTag(),
            ],
          ),
          !controller.isOrg
              ? _UserDefault(
                  isUserDefault: thesaurusInfo!.isUserDefault,
                  thesaurusCode: thesaurusInfo!.thesaurusCode,
                  index: index,
                )
              : const FSizedBox(),
          FSizedBox(
            height: 3,
          ),
        ],
      ),
    );
  }

  FWidget _thesaurusSourceTagText(String tagStr) {
    return FText(
      tagStr,
      style: TextStyle(
        fontSize: FFontSizes.BODY,
        color: _isActive ? Colors.white : Colors.black,
      ),
    );
  }

  TextStyle _buildTextStyleAccorrdingToIndex(double fontSize) {
    return TextStyle(
      fontSize: fontSize,
      color: _isActive ? Colors.white : Colors.black,
    );
  }

  FWidget _buidTitle(String title, {double titleFontSize = FFontSizes.H5}) {
    return FText(
      title,
      style: _buildTextStyleAccorrdingToIndex(titleFontSize),
    );
  }

  FWidget _buildThesaurusName() {
    return _buidTitle('${thesaurusInfo?.thesaurusName}');
  }

  FWidget _buildThesaurusCreationTitle() {
    return _buidTitle(i18nBook.remedical.creations.t,
        titleFontSize: FFontSizes.H6);
  }

  FWidget _buildThesaurusSourceTag() {
    String sourceTag = "";
    switch (thesaurusInfo!.thesaurusType) {
      case ThesaurusTypeEnum.Default:
        sourceTag = i18nBook.common.platformDefault.t;
        break;
      case ThesaurusTypeEnum.Organization:
        sourceTag = i18nBook.homePage.organizationEntries.t;
        break;
      case ThesaurusTypeEnum.Personal:
        sourceTag = i18nBook.remedical.selfCreated.t;
        break;
      default:
        sourceTag = i18nBook.common.platformDefault.t;
        break;
    }
    return _thesaurusSourceTagText(sourceTag);
  }

  bool _showBlankUIPlaceHolder() {
    if (controller.isOrg) {
      return thesaurusInfo!.thesaurusType != ThesaurusTypeEnum.Organization;
    } else {
      return thesaurusInfo!.thesaurusType != ThesaurusTypeEnum.Personal;
    }
  }

  _thesaurusUIPlaceHolder() {
    return _showBlankUIPlaceHolder()
        ? FSizedBox(
            height: 12,
          )
        : _showOperationUIPlaceHolder();
  }

  _getOperationArea() {
    return _showBlankUIPlaceHolder()
        ? FContainer()
        : FContainer(
            alignment: Alignment.centerRight,
            child: _showOperationUIArea(),
          );
  }

  _showOperationUIPlaceHolder() {
    return FContainer(
      margin: EdgeInsets.only(
        top: 6,
        bottom: 6,
      ),
      alignment: Alignment.centerLeft,
      width: 280,
      decoration: BoxDecoration(
        border: Border.all(
          color: Color.fromRGBO(216, 216, 216, 1),
          width: 0.25,
        ),
      ),
    );
  }

  FWidget _showOperationUIArea() {
    return FRow(
      crossAxisAlignment: CrossAxisAlignment.end,
      children: [
        FGestureDetector(
          name: "openEditThesaurusDialog",
          businessParent: this,
          onTap: () {
            controller.openEditThesaurusDialog(thesaurusInfo);
          },
          child: FMaterialTooltip(
            preferBelow: false,
            padding: EdgeInsets.all(5),
            message: i18nBook.common.edit.t,
            child: FIcon(
              Icons.edit,
              color: _isActive ? Colors.white : Colors.black,
            ),
          ),
        ),
        FSizedBox(
          width: 20,
        ),
        FGestureDetector(
          name: "removeThesaurus",
          businessParent: this,
          onTap: () {
            controller.isOrg
                ? controller.organizationEntryController
                    .removeOrgThesaurusAsync(
                    thesaurusInfo?.thesaurusCode ?? '',
                    this,
                  )
                : _removeThesaurusAsync(
                    thesaurusInfo?.thesaurusCode ?? '',
                  );
          },
          child: FMaterialTooltip(
            preferBelow: false,
            padding: EdgeInsets.all(5),
            message: i18nBook.common.delete.t,
            child: FIcon(
              Icons.delete,
              size: 20,
              color: _isActive ? Colors.white : Colors.black,
            ),
          ),
        ),
        FSizedBox(
          width: 15,
        ),
      ],
    );
  }

  /// 删除词条库
  ///
  /// [thesaurusCode] 词条编码
  void _removeThesaurusAsync(String thesaurusCode) async {
    FConfirmAlert.show(
      context: Get.context!,
      title: i18nBook.common.tip.t,
      subTitle: i18nBook.remedical.delteVocBaseConfirm.t,
      confrimLabel: i18nBook.common.confirm.t,
      cancelLabel: i18nBook.common.cancel.t,
      onConfirm: () async {
        await controller.busyHandle(
          () async {
            controller.removeThesaurusAsync(thesaurusCode);
          },
          text: i18nBook.remedical.deleting.t,
        );
      },
      businessParent: this,
    );
  }
}

class _UserDefault extends FStatefulWidget {
  _UserDefault({
    Key? key,
    required this.isUserDefault,
    required this.index,
    this.thesaurusCode,
  }) : super(key: key);

  final bool isUserDefault;
  final String? thesaurusCode;
  final int index;

  @override
  FState<_UserDefault> createState() => _UserDefaultState();
}

class _UserDefaultState extends FState<_UserDefault> {
  late bool _isActive = false;

  /// 词条控制器
  final controller = Get.find<VocabularyEntryController>();

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

  @override
  FWidget build(BuildContext context) {
    return FObx(() {
      controller.state.activeEntryIndex;
      if (kIsMobile) {
        _isActive = false;
      } else {
        _isActive = controller.state.thesaurusCode == widget.thesaurusCode;
      }
      return _buildUserDefault();
    });
  }

  TextStyle _buildTextStyleAccorrdingToIndex(double fontSize) {
    return TextStyle(
      fontSize: fontSize,
      color: _isActive ? Colors.white : Colors.black,
    );
  }

  FWidget _buildUserDefault({double titleFontSize = FFontSizes.H6}) {
    late bool userDefault = widget.isUserDefault;

    return FRow(
      children: [
        FText(
          i18nBook.common.defaultEntry.t,
          style: _buildTextStyleAccorrdingToIndex(titleFontSize),
        ),
        FSizedBox(
          width: 5,
        ),
        FSwitch(
          value: userDefault,
          inactiveThumbColor: Colors.green,
          inactiveTrackColor: Colors.grey.withAlpha(88),
          activeColor: Colors.white,
          activeTrackColor: Colors.green,
          onChanged: (value) {
            controller.personalEntryController
                .setUserDefaultThesaurusAsync(widget.thesaurusCode!);
          },
        )
      ],
    );
  }
}
