import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/router/desktop/names.dart';
import 'package:flyinsono/architecture/router/router.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:flyinsono/managers/interfaces/group.dart';
import 'package:flyinsono/pages/remote_controller/index.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:fis_ui/base_define/page.dart';
import 'package:fis_ui/index.dart';
import 'package:flyinsono/pages/user/group_chat/index.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'index.dart';
import 'package:fis_ui/values/font_sizes.dart';
import 'package:fis_ui/values/spacings.dart';
import 'package:fis_common/index.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:fis_theme/theme.dart';

class GroupListPage extends FisView<GroupListController> implements FPage {
  GroupListPage({Key? key}) : super(key: key);
  final groupManager = Get.find<IGroupManager>();
  @override
  String get pageName => 'GroupPage';

  @override
  FWidget build(BuildContext context) {
    FWidget body = _buildBody();
    if (kIsMobile) {
      return FScaffold(
        appBar: AppBar(
          elevation: 0,
          centerTitle: true,
          title: FText(
            i18nBook.user.myGroups.t,
            style: TextStyle(
              fontSize: FFontSizes.H6,
            ),
          ),
          leading: FIconButton(
            businessParent: this,
            name: "back",
            icon: FIcon(Icons.arrow_back_ios),
            onPressed: () {
              router.back();
            },
          ),
        ),
        body: body,
      );
    } else {
      return FRow(
        children: [
          body,
          _buildVerticalDivider(),
          FExpanded(
            child: FObx(() {
              if (controller.state.selectedGroupCode.isEmpty) {
                return NoDataWidget();
              }
              return GroupChatPage(
                args: ChatPageArgs(
                  userGroupCode: controller.state.selectedGroupCode,
                  groupName: controller.state.selectedGroup?.name ?? '',
                  deviceCodes:
                      controller.state.selectedGroup?.deviceCodes ?? [],
                  totalMembers:
                      controller.state.selectedGroup?.userCodes?.length ?? 0,
                ),
              );
            }),
          ),
        ],
      );
    }
  }

  FWidget _buildGroupCard(UserGroupDTO e) {
    return FMouseRegion(
      cursor: SystemMouseCursors.click,
      child: FGestureDetector(
        onTap: () {
          controller.state.selectedGroupCode = e.code!;
          if (kIsMobile) {
            Get.toNamed(
              RouteNames.User.GroupChat,
              arguments: ChatPageArgs(
                groupName: controller.state.selectedGroup?.name ?? '',
                userGroupCode: controller.state.selectedGroupCode,
                deviceCodes: controller.state.selectedGroup?.deviceCodes ?? [],
                totalMembers: controller.getGroupTotalMemberNum(
                  controller.state.selectedGroup,
                ),
              ),
            );
          } else {
            final groupChatController = Get.find<GroupChatController>();
            groupChatController.switchGroup(
              ChatPageArgs(
                userGroupCode: controller.state.selectedGroupCode,
                groupName: controller.state.selectedGroup?.name ?? '',
                deviceCodes: controller.state.selectedGroup?.deviceCodes ?? [],
                totalMembers: controller.getGroupTotalMemberNum(
                  controller.state.selectedGroup,
                ),
              ),
            );
          }
        },
        businessParent: this,
        name: e.name ?? '',
        child: FObx(() {
          bool isHighlight =
              controller.state.selectedGroupCode == e.code && !kIsMobile;
          return FContainer(
            padding: EdgeInsets.symmetric(horizontal: 10, vertical: 5),
            margin: EdgeInsets.symmetric(vertical: 5, horizontal: 15),
            height: 80,
            decoration: BoxDecoration(
              color:
                  isHighlight ? FTheme.ins.colorScheme.primary : Colors.white,
              borderRadius: BorderRadius.circular(8.0),
              border: Border.all(
                width: 1.0,
                color: Colors.white,
              ),
            ),
            child: FRow(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                _buildHeadImage(e.userCodes ?? [], e.deviceCodes ?? []),
                const FSizedBox(width: 15),
                FExpanded(
                  child: FColumn(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      FAlign(
                        alignment: Alignment.topLeft,
                        child: FText(
                          e.name ?? '',
                          style: TextStyle(
                            color: isHighlight ? Colors.white : Colors.black87,
                          ),
                        ),
                      ),
                      // FAlign(
                      //   alignment: Alignment.bottomRight,
                      //   child: _buildUpdateTime(
                      //     e.updateTime,
                      //     isHighlight,
                      //   ),
                      // ),
                    ],
                  ),
                ),
              ],
            ),
          );
        }),
      ),
    );
  }

  FWidget _buildHeadImage(List<String> users, List<String> devices) {
    // var userImage = FContainer(
    //   margin: EdgeInsets.all(0.5),
    //   width: 39,
    //   height: 39,
    //   child: FImage.asset(
    //     "assets/images/avatar_man.jpg",
    //   ),
    // );
    // var usImage = FContainer(
    //   margin: EdgeInsets.all(0.5),
    //   child: FImage.asset(
    //     "assets/images/mock_terminal.png",
    //   ),
    //   width: 39,
    //   height: 39,
    // );
    return QuickFWidget(
      AspectRatio(
        aspectRatio: 1,
        child: FContainer(
          width: 80,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.all(Radius.circular(8.0)), //圆角弧度
            color: Colors.grey[200],
          ),
          child: FClipRRect(
            borderRadius: BorderRadius.circular(8.0),
            child: FLayoutBuilder(builder: (context, constraints) {
              double imageSize = constraints.maxWidth / 2 - 1;
              return FWrap(
                alignment: WrapAlignment.center,
                children: [
                  if (users.length == 1 && devices.isEmpty) ...[
                    FImage.asset(
                      "assets/images/avatar_man.jpg",
                    ),
                  ] else if (users.length == 1) ...[
                    _buildUserImage(imageSize),
                    const FSizedBox(
                      width: 2,
                    ),
                  ] else if (users.length > 1) ...[
                    _buildUserImage(imageSize),
                    _buildUserImage(imageSize),
                  ],
                  if (devices.length == 1) ...[
                    _buildDeviceImage(imageSize),
                    const FSizedBox(
                      width: 2,
                    ),
                  ] else if (devices.length > 1) ...[
                    _buildDeviceImage(imageSize),
                    _buildDeviceImage(imageSize),
                  ],
                ],
              );
            }),
          ),
        ),
      ),
    );
  }

  FWidget _buildDeviceImage(double size) {
    return FContainer(
      margin: EdgeInsets.all(0.5),
      width: size,
      height: size,
      child: FImage.asset(
        "assets/images/mock_terminal.png",
      ),
    );
  }

  FWidget _buildUserImage(double size) {
    return FContainer(
      margin: EdgeInsets.all(0.5),
      width: size,
      height: size,
      child: FImage.asset(
        "assets/images/avatar_man.jpg",
      ),
    );
  }

  FWidget _buildBody() {
    return FSafeArea(
      child: FContainer(
        width: kIsMobile ? null : 350,
        child: FColumn(
          children: [
            FSearchInput(
              businessParent: this,
              hintText: i18nBook.common.search.t,
              serchOnPressed: () async {
                await controller.searchGrooups();
              },
              controller: controller.searchController,
            ),
            FSizedBox(
              height: 10,
            ),
            FObx(() {
              if (controller.state.groups.isEmpty) {
                return FExpanded(
                  child: NoDataWidget(),
                );
              } else {
                return FExpanded(
                  child: FListView(
                    shrinkWrap: true,
                    children: controller.state.groups
                        .map(
                          (e) => _buildGroupCard(e),
                        )
                        .toList(),
                  ),
                );
              }
            }),
          ],
        ),
      ),
    );
  }

  FWidget _buildVerticalDivider() {
    return FVerticalDivider(
      color: Colors.grey[300],
      width: 1,
      thickness: 1,
    );
  }

  FWidget _buildUpdateTime(DateTime? updateTime, bool highlight) {
    if (updateTime == null) {
      return FSizedBox();
    } else {
      var timeStr = DateFormat("yyyy-MM-dd HH:MM").format(
        DateTime.fromMillisecondsSinceEpoch(DateTime.tryParse(
          updateTime.toString(),
        )?.millisecondsSinceEpoch as int),
      );
      return FText(
        timeStr,
        style: TextStyle(
          color: highlight ? Colors.white : Colors.grey[400],
          fontSize: 12,
        ),
      );
    }
  }
}
