import 'package:fis_i18n/i18n.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:fis_ui/values/spacings.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/services/entity/local_setting.dart';
import 'package:flyinsono/global.dart';

import 'controller.dart';
import 'widgets/device_info_card.dart';
import 'widgets/device_live_panel.dart';
import 'widgets/recorder.dart';
import 'package:fis_ui/widgets/layout/button_group.dart';

class DeviceLiveDetailDesktopPage
    extends FisView<DeviceLiveDetailDesktopController> implements FPage {
  @override
  late final String pageName;

  late final state = controller.state;

  DeviceLiveDetailDesktopPage({super.key}) {
    pageName = "DeviceLiveDetail";
  }

  @override
  FWidget build(BuildContext context) {
    final body = _buildBody(context);
    if (state.canRecordWindow) {
      return FStack(
        children: [
          body,
          _buildWinRecordMark(),
        ],
      );
    } else {
      return body;
    }
  }

  FWidget _buildBody(BuildContext context) {
    return FRow(
      children: [
        FExpanded(
          child: FObx(() {
            return FContainer(
              color: Colors.black,
              child: _buildLiveViewRegion(),
            );
          }),
        ),
        FObx(() {
          final isCollapsed = state.isListPanelCollapsed;
          if (isCollapsed) {
            return _buildExpandButton();
          } else {
            return _buildDeviceListRegion(context);
          }
        }),
      ],
    );
  }

  /// 构建列表面板折叠按钮
  FWidget _buildCollapseButton() {
    const borderRadius = BorderRadius.only(
      topRight: Radius.circular(8),
      bottomRight: Radius.circular(8),
    );
    return FContainer(
      height: 80,
      width: 22,
      decoration: const BoxDecoration(
        color: Colors.black54,
        borderRadius: borderRadius,
      ),
      child: FMouseRegion(
        cursor: SystemMouseCursors.click,
        child: FGestureDetector(
          name: "DeviceLive_CollapseDeviceList",
          businessParent: this,
          child: FHoverHighlightContainer(
            decoration: const BoxDecoration(
              borderRadius: borderRadius,
            ),
            child: const FIcon(
              Icons.arrow_forward_ios_outlined,
              size: FFontSizes.H4,
              color: Colors.white,
            ),
          ),
          onTap: () {
            controller.collapseListPanel();
          },
        ),
      ),
    );
  }

  /// 构建设备列表区域
  FWidget _buildDeviceListRegion(BuildContext context) {
    return FStack(
      children: [
        FContainer(
          color: const Color.fromARGB(255, 51, 51, 51),
          width: 320,
          child: FColumn(
            children: [
              /// 列表头部
              _buildListPanelHeader(context),
              FDivider(
                color: Colors.grey.shade400,
                height: 1,
              ),
              // 列表主题
              FExpanded(
                child: _buildListPanelMain(context),
              ),
              if (state.canRecordWindow) ...[
                const FDivider(color: Colors.white),
                // 录制栏位
                FSizedBox(height: 40, child: _buildWinRecordBar(context)),
              ],
            ],
          ),
        ),
        FPositioned(
          top: 0,
          bottom: 0,
          left: 0,
          child: FCenter(
            child: _buildCollapseButton(),
          ),
        ),
      ],
    );
  }

  /// 构建列表面板展开按钮
  FWidget _buildExpandButton() {
    return FContainer(
      width: 24,
      height: double.infinity,
      color: const Color.fromARGB(255, 81, 81, 81),
      child: FMouseRegion(
        cursor: SystemMouseCursors.click,
        child: FGestureDetector(
          name: "DeviceLive_CollapseDeviceList",
          businessParent: this,
          child: FHoverHighlightContainer(
            child: const FIcon(
              Icons.arrow_back_ios_outlined,
              size: FFontSizes.H4,
              color: Colors.white,
            ),
          ),
          onTap: () {
            controller.expandListPanel();
          },
        ),
      ),
    );
  }

  /// 构建列表面板头部
  FWidget _buildListPanelHeader(BuildContext context) {
    return FSizedBox(
      height: 50,
      child: FStack(
        children: [
          FCenter(
            child: FText(
              i18nBook.live.clickToViewOtherDeviceLive.t,
              style: TextStyle(
                color: Colors.white,
                fontSize: FFontSizes.H6,
              ),
            ),
          ),
          FPositioned(
            right: 2,
            top: 0,
            bottom: 0,
            child: FIconButton(
              name: "RefreshLiveDeviceList",
              businessParent: this,
              icon: FIcon(
                Icons.refresh_outlined,
                color: Theme.of(context).primaryColor,
              ),
              iconSize: 24,
              onPressed: () {
                controller.reloadList();
              },
            ),
          ),
        ],
      ),
    );
  }

  /// 构建列表面板主体
  FWidget _buildListPanelMain(BuildContext context) {
    return FContainer(
      padding: const EdgeInsets.symmetric(vertical: 2),
      child: FThemeWidget(
        data: Theme.of(context).copyWith(
          scrollbarTheme: ScrollbarThemeData(
            thumbColor: MaterialStateProperty.all(Colors.grey),
          ),
        ),
        child: FScrollbar(
          isAlwaysShown: true,
          controller: controller.listScrollController,
          child: FObx(
            () {
              return FListView.builder(
                controller: controller.listScrollController,
                itemCount: state.deviceList.length,
                itemBuilder: (context, index) {
                  return DeviceInfoCard(index);
                },
              );
            },
          ),
        ),
      ),
    );
  }

  // 构建直播展示区域
  FWidget? _buildLiveViewRegion() {
    final count = state.liveIndexList.length;
    if (count == 0) return null;

    return FLayoutBuilder(builder: (context, constraints) {
      return _buildMultiViewGrid(
        count,
        constraints.maxWidth,
        constraints.maxHeight,
      );
    });
  }

  FWidget _buildMultiViewGrid(int count, double width, double height) {
    final scrollController = ScrollController();
    double aspect = 1.0;
    int horCount = 1; // 水平轴数量
    int verCount = 1; // 垂直轴数量

    if (count == 1) {
      // 1x1
      horCount = 1;
      verCount = 1;
      aspect = width / height;
    } else if (count == 2) {
      // 2x1
      horCount = 2;
      verCount = 1;
      aspect = width / 2 / height;
    } else if (count <= 4) {
      // 2x2
      horCount = 2;
      verCount = 2;
      aspect = width / height;
    } else {
      if (width > height) {
        // 宽大于高，3x2
        horCount = 3;
        verCount = 2;
      } else {
        // 高大于宽，2x3
        horCount = 2;
        verCount = 3;
      }
      final w = width / horCount;
      final h = height / verCount;
      aspect = w / h;
    }
    return FScrollbar(
      controller: scrollController,
      trackVisibility: false,
      thumbVisibility: false,
      notificationPredicate: (notification) => true,
      child: FGridView.builder(
        controller: scrollController,
        itemCount: count,
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: horCount,
          mainAxisSpacing: 2,
          crossAxisSpacing: 2,
          childAspectRatio: aspect,
        ),
        itemBuilder: (BuildContext context, int index) {
          return LayoutBuilder(builder: (_, constraints) {
            final stateIndex = state.liveIndexList[index];
            final model = state.deviceList[stateIndex];
            final liveInfo = model.liveInfo!;
            final mainSource = liveInfo.sources.first;
            final mainWidth = mainSource.width;
            final mainHeight = mainSource.height;

            final id = index + 1;
            final showRightSpacing = id % horCount > 0;
            final showBottomSpacing = id ~/ horCount < verCount;
            const border = BorderSide(color: Colors.white);

            final shortCodeSign = FText(
              model.dto.displayName!,
              style: TextStyle(
                color: Colors.yellow,
                fontSize: FFontSizes.H4,
                fontWeight: FontWeight.bold,
              ),
            ); // 唯一码标识
            return Container(
              decoration: BoxDecoration(
                color: Colors.black,
                border: Border(
                  right: showRightSpacing ? border : BorderSide.none,
                  bottom: showBottomSpacing ? border : BorderSide.none,
                ),
              ),
              child: Stack(
                children: [
                  Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Container(height: 1, color: Colors.black),
                      Expanded(
                        child: Container(
                          width: constraints.maxWidth,
                          height: constraints.maxWidth / mainWidth * mainHeight,
                          child: DeviceLivePanel(stateIndex),
                        ),
                      ),
                      Container(height: 1, color: Colors.black),
                    ],
                  ),
                  FPositioned(
                    top: FFontSizes.H1,
                    left: FFontSizes.H6,
                    child: shortCodeSign,
                  ),
                ],
              ),
            );
          });
        },
      ),
    );
  }

  /// 右下角录制栏
  FWidget _buildWinRecordBar(BuildContext context) {
    return FObx(() {
      final children = <FWidget>[];
      if (controller.state.isWinRecordStarted) {
        // 暂停录制
        children.add(_buildWinRecordPauseBtn());

        // 结束录制
        children.add(
          FElevatedButton(
            style: ButtonStyle(
              backgroundColor: MaterialStatePropertyAll(Colors.red),
            ),
            child: FText(i18nBook.realTimeConsultation.endRecording.t),
            onPressed: () {
              if (LocalSetting.ins.isUseSecondWindow == false) {
                GlobalFullScreenEvent.send(false);
              }
              controller.stopWinRecord();
            },
            businessParent: this,
            name: 'StopRecording',
          ),
        );
      } else {
        // 开始录制
        children.add(
          FElevatedButton(
            child: FText(i18nBook.realTimeConsultation.fullRecording.t),
            onPressed: () {
              if (LocalSetting.ins.isUseSecondWindow == false) {
                GlobalFullScreenEvent.send(true);
              }
              controller.startWinRecord();
            },
            businessParent: this,
            name: 'StartRecording',
          ),
        );
      }

      return FContainer(
          padding: EdgeInsets.symmetric(horizontal: FSpacings.M),
          alignment: Alignment.center,
          child: FButtonGroup(
            spacing: 10,
            buttonPadding: 18,
            children: children,
          ));
    });
  }

  FWidget _buildWinRecordMark() {
    return FObx(() {
      if (controller.state.isWinRecordStarted) {
        return FPositioned(
          top: FSpacings.M,
          left: FSpacings.M,
          child: WindowRecorderMark(
            controller: controller.windowRecorderController!,
          ),
        );
      } else {
        return const FSizedBox();
      }
    });
  }

  /// 录制暂停/继续 按钮
  FWidget _buildWinRecordPauseBtn() {
    final recordContoller = controller.windowRecorderController!;
    if (recordContoller.running) {
      return FElevatedButton.icon(
        icon: Icon(Icons.pause),
        label: FText(i18nBook.realTimeConsultation.pauseFullRecording.t),
        onPressed: () {
          recordContoller.pause();
        },
        businessParent: this,
        name: 'PauseRecording',
      );
    } else {
      return FElevatedButton.icon(
        icon: Icon(Icons.play_arrow),
        label: FText(i18nBook.realTimeConsultation.continueFullRecording.t),
        onPressed: () {
          recordContoller.resume();
        },
        businessParent: this,
        name: 'ResumeRecording',
      );
    }
  }
}
