import 'package:fis_common/logger/logger.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:fis_jsonrpc/services/liveConsultation.m.dart';
import 'package:fis_jsonrpc/services/notification.m.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_ui/interface/interactive_container.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/router/index.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/pages/schedule/calendar/controller.dart';
import 'package:flyinsono/pages/schedule/calendar/calendar_page/detail_dialog/schedule_detail_dialog.dart';
import 'package:flyinsono/pages/schedule/calendar/models.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/pages/schedule/calendar/utils/calendar_utils.dart';
import 'package:flyinsono/pages/schedule/schedule_notification/schedule_notification_binding.dart';
import 'package:flyinsono/rpc.dart';
import 'package:flyinsono/views/desktop/real_time_consultation/widgets/member_avatars.dart';
import 'package:get/get.dart';

class ConsultationSchedulePopup extends FStatefulWidget
    implements FInteractiveContainer {
  const ConsultationSchedulePopup({
    Key? key,
    required this.scheduleData,
    required this.onClose,
  }) : super(key: key);

  /// 日程数据
  final ScheduleModel scheduleData;

  final VoidCallback onClose;

  @override
  FState createState() => ConsultationSchedulePopupState();

  @override
  String get pageName => "SchedulePopup";
}

class ConsultationSchedulePopupState extends FState<ConsultationSchedulePopup> {
  final ScrollController _scrollController = ScrollController();
  CalendarController calendarController = Get.find<CalendarController>();
  List<ConsultationMemberDTO> _members = [];
  int _memberCount = 0;
  int _memberAcceptCount = 0;
  String _expertUserName = '';
  @override
  void initState() {
    super.initState();
  }

  @override
  void didUpdateWidget(covariant ConsultationSchedulePopup oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.scheduleData.content != widget.scheduleData.content) {
      _getDetailInfo();
    }
  }

  /// 查询详情
  void _getDetailInfo() async {
    try {
      final result = await rpc.liveConsultation.findConsultationDetailAsync(
        FindConsultationDetailRequest(
          token: Store.user.token,
          consultationCode: widget.scheduleData.content,
        ),
      );
      _expertUserName = result.expertUserName ?? '';
      _members = result.consultationMembers ?? [];
      _memberCount = result.consultationMembers?.length ?? 0;
      _memberAcceptCount = result.consultationMembers
              ?.where(
                (element) =>
                    element.memberStatus ==
                    LiveConsultationMemberStatus.Accepted,
              )
              .length ??
          0;
      setState(() {});
    } catch (e) {
      logger.e("findConsultationDetailAsync exception:", e);
    }
  }

  @override
  FWidget build(BuildContext context) {
    return FAlwaysScrollListView(
      scrollController: _scrollController,
      child: QuickFWidget(ScrollConfiguration(
        behavior: ScrollConfiguration.of(context).copyWith(scrollbars: false),
        child: FListView(
          shrinkWrap: true,
          children: [
            _buildScheduleDetailCard(),
          ],
        ),
      )),
    );
  }

  /// 构建icon
  FWidget _buildIcon({
    required IconData icon,
    required double size,
  }) {
    return FIcon(
      icon,
      size: size,
      color: const Color.fromRGBO(116, 118, 119, 1),
    );
  }

  /// 构建icon按钮
  FWidget _buildIconButton({
    required VoidCallback onPressed,
    required IconData icon,
  }) {
    return FMaterial(
      color: Colors.transparent,
      child: FIconButton(
        businessParent: widget,
        name: 'detail_card_icon_button',
        splashRadius: 20,
        onPressed: onPressed,
        icon: _buildIcon(
          icon: icon,
          size: 20,
        ),
      ),
    );
  }

  /// 日程卡片视图列表
  FWidget _buildScheduleDetailCard() {
    return FColumn(
      mainAxisSize: MainAxisSize.min,
      children: [
        FPadding(
          padding: const EdgeInsets.symmetric(horizontal: 8),
          child: FColumn(
            children: [
              _buildScheduleHeadActionBar(),
              _buildScheduleLayoutItem(
                iconWidget: FSizedBox(
                  width: 18,
                  child: FCircleAvatar(
                    radius: 6,
                    backgroundColor: widget.scheduleData.type.color,
                  ),
                ),
                scheduleItemWidget: FText(
                  "${widget.scheduleData.title} - ${widget.scheduleData.type.typeName}",
                ),
              ),
              FSizedBox(
                height: 10,
              ),
              _buildScheduleLayoutItem(
                iconWidget: _buildIcon(
                  icon: Icons.av_timer_rounded,
                  size: 18,
                ),
                scheduleItemWidget: FText(
                  CalendarUtils.formatDateRange(
                    widget.scheduleData.startTime,
                    widget.scheduleData.endTime,
                  ),
                ),
              ),
              FSizedBox(
                height: 10,
              ),
              _buildScheduleLayoutItem(
                iconWidget: _buildIcon(
                  icon: Icons.badge_outlined,
                  size: 18,
                ),
                scheduleItemWidget: FText(
                    '$_expertUserName ${i18nBook.notification.expertNameWithBrackets.t}'),
              ),
              FSizedBox(
                height: 10,
              ),
              if (_memberCount > 0)
                _buildScheduleLayoutItem(
                  iconWidget: _buildIcon(
                    icon: Icons.people_alt_outlined,
                    size: 18,
                  ),
                  scheduleItemWidget: FRow(
                    mainAxisSize: MainAxisSize.max,
                    children: [
                      FText(
                        i18nBook.notification.inviteSomeoneToConsultation
                            .translate([
                          _memberCount.toString(),
                          _memberAcceptCount.toString(),
                        ]),
                      ),
                      FExpanded(child: FSizedBox()),
                      FInkWell(
                        onTap: () {
                          widget.onClose.call();
                          router.dialog(
                            () => ScheduleDetailDialog(),
                            transitionDuration: Duration(milliseconds: 500),
                            transitionCurve: Curves.easeInOut,
                            binding: ScheduleNotificationBinding(
                                consultationCode: widget.scheduleData.content),
                          );
                        },
                        child: FText(
                          i18nBook.notification.showAll.t,
                          style: TextStyle(
                            fontSize: 12,
                            color: Colors.grey,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              FSizedBox(
                height: 5,
              ),
              FMemberAvatars(
                members: _members,
                onlyShowFive: true,
              )
            ],
          ),
        ),
        const FSizedBox(
          height: 15,
        ),
        FContainer(
          decoration: const BoxDecoration(
            border: Border(
              top: BorderSide(
                color: Color.fromRGBO(238, 238, 238, 1),
                width: 1,
              ),
            ),
          ),
          padding: const EdgeInsets.symmetric(horizontal: 8),
          child: _buildSchedulebottomActionBar(),
        ),
      ],
    );
  }

  /// 日程卡片顶部操作栏
  FWidget _buildScheduleHeadActionBar() {
    return FSizedBox(
      height: 50,
      child: FRow(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          /// TODO:[Gavin] 占位功能区，暂时屏蔽，待实现
          // _buildIconButton(
          //   onPressed: () {},
          //   icon: Icons.delete_outlined,
          // ),
          // _buildIconButton(
          //   onPressed: () {},
          //   icon: Icons.launch_rounded,
          // ),
          _buildIconButton(
            onPressed: () {
              widget.onClose.call();
            },
            icon: Icons.close,
          ),
        ],
      ),
    );
  }

  /// 日程卡片底部操作栏
  FWidget _buildSchedulebottomActionBar() {
    return FSizedBox(
      height: 50,
      child: FRow(
        children: [
          FSizedBox(
            width: 10,
          ),
          FInkWell(
            onTap: () {
              widget.onClose.call();
              router.dialog(
                () => ScheduleDetailDialog(),
                transitionDuration: Duration(milliseconds: 500),
                transitionCurve: Curves.easeInOut,
                binding: ScheduleNotificationBinding(
                    consultationCode: widget.scheduleData.content),
              );
            },
            child: FText(
              i18nBook.remedical.viewDetail.t,
              style: TextStyle(
                color: Colors.black54,
              ),
            ),
          ),
          FExpanded(
            child: FRow(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                /// TODO:[Gavin] 占位功能区，暂时屏蔽，待实现
                // _buildIconButton(
                //   onPressed: () {},
                //   icon: Icons.check_circle_outlined,
                // ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 日程卡片单行布局
  FWidget _buildScheduleLayoutItem({
    required FWidget iconWidget,
    required FWidget scheduleItemWidget,
  }) {
    return FContainer(
      padding: const EdgeInsets.only(
        left: 10,
        right: 10,
      ),
      child: FRow(
        children: [
          FContainer(
            margin: const EdgeInsets.only(
              left: 5,
              right: 10,
            ),
            child: iconWidget,
          ),
          FExpanded(child: scheduleItemWidget),
        ],
      ),
    );
  }
}
