import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:keyboard/base/base_view.dart';
import 'package:keyboard/data/bean/upload_info.dart';
import 'package:keyboard/module/intimacy_analyse/intimacy_analyse_upload/widget/upload_nine_grid.dart';
import 'package:keyboard/module/intimacy_analyse/widget/creating_loading_widget.dart';
import '../../../../data/bean/image_viewer_item.dart';
import '../../../../data/bean/option_select_config.dart';
import '../../../../data/bean/option_select_item.dart';
import '../../../../data/bean/reply_mode.dart';
import '../../../../resource/assets.gen.dart';
import '../../../../resource/colors.gen.dart';
import '../../../../resource/string.gen.dart';
import '../../../../utils/prefix_util.dart';
import '../../../../utils/step_card_util.dart';
import '../../../../utils/upload/file_data_source_util.dart';
import '../../../../widget/actionbtn/action_btn.dart';
import '../../../../widget/gradient_btn.dart';
import '../../../../widget/gradient_text.dart';
import '../../image_viewer/image_viewer_page.dart';
import '../../intimacy_analyse_upload/popup/reply_mode_select_popup.dart';
import '../../intimacy_analyse_upload/widget/upload_item_widget.dart';
import '../../widget/option_select_widget.dart';
import '../../widget/step_card.dart';
import 'package:keyboard/module/intimacy_analyse/screenshot_reply/scan_image_reply/scan_image_reply_controller.dart';

/// 识图回复Tab页
class ScanImageReplyView extends BaseView<ScanImageReplyController> {
  ScanImageReplyView({super.key});

  /// 回复模式，切换按钮的GlobalKey
  final GlobalKey _replyModeSwitchBtnAnchorKey = GlobalKey();

  @override
  Color backgroundColor() {
    return Colors.transparent;
  }

  @override
  Widget buildBody(BuildContext context) {
    return Stack(
      children: [
        SingleChildScrollView(
          child: Obx(() {
            bool isSample = controller.uploadInfo.value == null;
            if (isSample) {
              return Column(
                children: [
                  // 上传截图的卡片
                  _buildUploadScreenshotCard(true),
                  SizedBox(height: 14.h),
                ],
              );
            } else {
              return Column(
                children: [
                  // 上传截图的卡片
                  _buildUploadScreenshotCard(false),
                  SizedBox(height: 14.h),
                  // 选项卡片
                  _buildOptionCard(),
                  // 回复语气列表卡片
                  _buildReplyToneListCard(),
                  // 距离底部有一定间距
                  _buildBottomSpace(),
                ],
              );
            }
          }),
        ),
        // 上传截图按钮
        Positioned.fill(
          child: Align(
            alignment: Alignment.bottomCenter,
            child: _buildBottomLayout(context),
          ),
        ),
      ],
    );
  }

  /// 底部间距
  Widget _buildBottomSpace() {
    return Obx(() {
      // 生成中，或已生成，底部高度降低
      if (controller.isResultGenerating.value ||
          controller.hasScanResult.value) {
        return SizedBox(height: 20.h);
      }
      // 否则留出距离给底部显示
      return SizedBox(height: 90.h);
    });
  }

  /// 上传截图的卡片
  /// [isSample] 是否是样例图片
  Widget _buildUploadScreenshotCard(bool isSample) {
    return Obx(() {
      Widget actionBtn;

      // 例子，示例图
      if (isSample) {
        actionBtn = Container(
          padding: EdgeInsets.all(6.w),
          decoration: BoxDecoration(
            color: ColorName.black28,
            borderRadius: BorderRadius.circular(9.r),
          ),
          child: Text(
            StringName.intimacyAnalyseSampleImage,
            style: TextStyle(
              color: ColorName.white,
              fontSize: 12.sp,
              fontWeight: FontWeight.w500,
            ),
          ),
        );
      } else {
        // 重新上传按钮
        actionBtn = GestureDetector(
          onTap: () {
            BuildContext? context = Get.context;
            if (context != null) {
              controller.clickUploadScreenshotBtn(context);
            }
          },
          child: Container(
            padding: EdgeInsets.symmetric(vertical: 8.h, horizontal: 12.w),
            decoration: BoxDecoration(
              color: ColorName.black80,
              borderRadius: BorderRadius.circular(30.r),
            ),
            child: Text(
              StringName.intimacyAnalyseReUpload,
              style: TextStyle(
                color: ColorName.white,
                fontSize: 12.sp,
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
        );
      }

      Widget imageWidget;
      // 样例图片
      if (isSample) {
        imageWidget = Assets.images.iconUploadScreenshotSampleImage.image(
          width: 288.w,
          height: 290.h,
          fit: BoxFit.cover,
        );
      } else {
        // 上传
        imageWidget = UploadItemWidget(
          imageUploadInfo: controller.uploadInfo.value!,
          hasDeleteBtn: false,
          // 失败时的遮罩
          uploadFailMaskWidget: UploadFailMaskWidget(
            iconWidget: Assets.images.iconUploadFail.image(
              width: 40.w,
              height: 40.w,
            ),
            spaceWidget: SizedBox(height: 12.h),
            textWidget: Text(
              StringName.intimacyAnalyseUploadFail,
              style: TextStyle(
                color: ColorName.white,
                fontSize: 16.sp,
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
          onClickItemCallback: (UploadInfo uploadInfo) {
            // 预览图片
            ImageViewerItem imageViewerItem;
            String src = FileDataSourceUtil.getFileDataSourceSrc(uploadInfo);
            // 远程图片
            if (PrefixUtil.isRemoteImage(src)) {
              imageViewerItem = ImageViewerItem.network(src);
            } else {
              // 本地图片
              imageViewerItem = ImageViewerItem.file(src);
            }
            ImageViewerPage.start([imageViewerItem]);
          },
          onClickDeleteCallback: (UploadInfo uploadInfo) {
            controller.deleteUploadInfo(uploadInfo);
          },
        );
      }

      // 识图回复，只有1张图
      int uploadItemCount = 1;
      Mode mode =
          controller.uploadInfo.value == null ? Mode.preview : Mode.edit;
      return StepCard(
        bgImageProvider: StepCardUtil.getCardBgImageProvider(
          itemCount: uploadItemCount,
          sceneType: controller.uploadSceneType,
          mode: mode,
        ),
        topTitleWidget: StepTitleWidget(
          stepTitle: StringName.intimacyUploadScreenshot,
          stepDesc: StringName.intimacyAnalyseUploadScreenshotCardTip,
        ),
        topIconWidget: Assets.images.iconIntimacyAnalyseUploadTop.image(
          height: 63.h,
          width: 103.w,
        ),
        // 顶部图标的位置
        topIconWidgetLocation: StepCardUtil.calculateTopIconWidgetLocation(
          itemCount: uploadItemCount,
          sceneType: controller.uploadSceneType,
          mode: mode,
        ),
        contentWidget: Column(
          children: [
            Container(
              width: 312.w,
              height: 314.h,
              margin: EdgeInsets.only(left: 12.w, top: 17.h, right: 12.w),
              padding: EdgeInsets.all(12.w),
              decoration: BoxDecoration(
                color: ColorName.white,
                borderRadius: BorderRadius.circular(16.r),
              ),
              child: Stack(
                children: [
                  Positioned.fill(
                    child: Container(
                      padding: EdgeInsets.all(12.w),
                      child: ClipRRect(
                        // 图片裁切成圆角
                        borderRadius: BorderRadius.circular(16.r),
                        child: imageWidget,
                      ),
                    ),
                  ),
                  Positioned(right: 0, bottom: 0, child: actionBtn),
                ],
              ),
            ),
          ],
        ),
      );
    });
  }

  /// 选项卡片
  Widget _buildOptionCard() {
    return Obx(() {
      if (controller.replyToneList.isNotEmpty) {
        return SizedBox.shrink();
      }
      return Container(
        width: double.maxFinite,
        margin: EdgeInsets.only(left: 14.w, right: 14.w, bottom: 14.h),
        // 圆角背景
        decoration: BoxDecoration(
          gradient: LinearGradient(
            colors: [Color(0xFFEFE9FF), Color(0xFFFBFAFF)],
            begin: Alignment.topCenter,
            end: Alignment.bottomRight,
          ),
          shape: BoxShape.rectangle,
          border: Border.all(color: ColorName.white80, width: 1.w),
          borderRadius: BorderRadius.all(Radius.circular(20.r)),
        ),
        child: Column(
          children: [
            Container(
              margin: EdgeInsets.only(
                left: 12.w,
                top: 17.h,
                right: 12.w,
                bottom: 12.h,
              ),
              padding: EdgeInsets.only(
                left: 12.w,
                top: 12.h,
                right: 12.w,
                bottom: 12.h,
              ),
              decoration: BoxDecoration(
                color: ColorName.white,
                borderRadius: BorderRadius.circular(16.r),
              ),
              child: Column(
                children: [
                  // 添加选项行
                  for (var optionConfig
                      in controller.replyToneOptionSelectConfigList)
                    _buildOptionRow(optionConfig),
                ],
              ),
            ),
          ],
        ),
      );
    });
  }

  /// 回复语气列表卡片
  Widget _buildReplyToneListCard() {
    return Obx(() {
      Widget resultWidget = Container(
        margin: EdgeInsets.only(left: 12.w, right: 12.w),
        decoration: BoxDecoration(
          // 渐变背景
          gradient: LinearGradient(
            colors: [Color(0xFFEFE9FF), Color(0xFFFBFAFF)],
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
          ),
          borderRadius: BorderRadius.all(Radius.circular(20.r)),
        ),
        child: Column(
          children: [
            Container(
              margin: EdgeInsets.only(top: 10.h, bottom: 18.h),
              child: Column(
                children: [
                  Row(
                    children: [
                      Expanded(
                        child: Row(
                          children: [
                            // 回复语气的标题
                            SizedBox(
                              width: 80.w,
                              height: 40.h,
                              child: Stack(
                                children: [
                                  // 底部的横线
                                  Positioned(
                                    left: 15.w,
                                    bottom: 10.h,
                                    child: Container(
                                      width: 57.w,
                                      height: 7.h,
                                      color: Color(0xFFCEB6FF),
                                    ),
                                  ),
                                  Positioned(
                                    left: 0,
                                    bottom: 0,
                                    child: Container(
                                      margin: EdgeInsets.only(
                                        left: 16.w,
                                        bottom: 10.h,
                                      ),
                                      child: // 标题
                                          Text(
                                        StringName.intimacyAnalyseReplyTone,
                                        style: TextStyle(
                                          color: ColorName.black80,
                                          fontSize: 14.sp,
                                          fontWeight: FontWeight.w700,
                                        ),
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            // 当前选择的回复语气
                            Text(
                              controller
                                      .currentSelectReplyToneOption
                                      .value
                                      ?.name ??
                                  "",
                              style: TextStyle(
                                color: ColorName.black80,
                                fontSize: 14.sp,
                                fontWeight: FontWeight.w500,
                              ),
                            ),
                          ],
                        ),
                      ),
                      // 再试试按钮
                      _buildRetryBtn(),
                      SizedBox(width: 10.w),
                    ],
                  ),
                  controller.isResultGenerating.value
                      ? Container(
                        padding: EdgeInsets.only(top: 33.h, bottom: 52.h),
                        child: CreatingLoadingWidget(
                          tipTextWidget: Text(
                            StringName.intimacyAnalyseIng2,
                            style: TextStyle(
                              fontSize: 14.sp,
                              color: ColorName.black60,
                              fontWeight: FontWeight.w400,
                            ),
                          ),
                        ),
                      )
                      :
                      // 回复语气列表
                      Column(
                        children: [
                          for (var replyTone in controller.replyToneList)
                            _buildReplyToneListItem(replyTone),
                        ],
                      ),
                ],
              ),
            ),
          ],
        ),
      );
      // 生成中，展示组件
      if (controller.isResultGenerating.value) {
        return resultWidget;
      } else {
        // 未生成，不显示
        if (!controller.hasScanResult.value) {
          return SizedBox.shrink();
        } else {
          // 已生成，显示
          return resultWidget;
        }
      }
    });
  }

  /// 再试试按钮
  Widget _buildRetryBtn() {
    return GestureDetector(
      onTap: () {
        controller.clickRetryBtn();
      },
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 28.w, vertical: 8.h),
        decoration: BoxDecoration(
          // 渐变背景
          gradient: LinearGradient(
            colors: [ColorName.purpleGradient3, ColorName.purpleGradient4],
            begin: Alignment.centerLeft,
            end: Alignment.centerRight,
          ),
          borderRadius: BorderRadius.all(Radius.circular(30.r)),
        ),
        child: Text(
          StringName.retry,
          style: TextStyle(
            color: ColorName.white,
            fontSize: 14.sp,
            fontWeight: FontWeight.w400,
          ),
        ),
      ),
    );
  }

  /// 回复语气列表条目
  Widget _buildReplyToneListItem(String replyTone) {
    return Container(
      margin: EdgeInsets.only(left: 12.w, right: 12.w, top: 10.h),
      decoration: BoxDecoration(
        color: ColorName.white,
        borderRadius: BorderRadius.circular(16.r),
        boxShadow: [
          BoxShadow(
            // 阴影颜色
            color: Color(0x61D2D2D2),
            // 模糊半径（值越大越模糊）
            blurRadius: 3.8,
            // 阴影扩散范围（正值为扩大，负值为缩小）
            spreadRadius: 1,
            // 阴影偏移量（x, y）
            offset: Offset(0, 2),
          ),
        ],
      ),
      child: Row(
        children: [
          // 文字
          Expanded(
            child: Container(
              margin: EdgeInsets.only(left: 21.w, top: 12.h, bottom: 12.h),
              child: Text(
                replyTone,
                // maxLines: 1,
                style: TextStyle(
                  // overflow: TextOverflow.ellipsis,
                  color: ColorName.black80,
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ),
          ),
          // 图标
          Visibility(
            visible: replyTone.isNotEmpty,
            child: GestureDetector(
              onTap: () {
                // 拷贝回复语气
                controller.copyReplyTone(replyTone);
              },
              child: Container(
                margin: EdgeInsets.only(right: 14.w),
                child: Assets.images.iconActionCopy.image(
                  width: 18.w,
                  height: 18.w,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建一行选择选项行
  Widget _buildOptionRow(OptionSelectConfig config) {
    return Column(
      children: [
        // 选择项
        OptionSelectWidget(
          optionSelect: config,
          optionSelectCallback: (
            OptionSelectConfig rowConfig,
            OptionSelectItem optionItem,
          ) {
            controller.selectReplyToneOption(rowConfig, optionItem);
          },
        ),
        SizedBox(height: 20.h),
      ],
    );
  }

  /// 上传截图按钮
  Widget _buildUploadScreenshotBtn(BuildContext context) {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w),
      width: double.maxFinite,
      child: GradientTextBtn(
        StringName.intimacyUploadScreenshot,
        onPressed: () {
          controller.clickUploadScreenshotBtn(context);
        },
      ),
    );
  }

  /// 获取回复按钮
  Widget _buildGetReplayBtn() {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 14.h),
      width: double.maxFinite,
      child: GradientTextBtn(
        StringName.intimacyAnalyseGetReply,
        onPressed: () {
          controller.clickGetReplyBtn();
        },
      ),
    );
  }

  /// Ai模型切换按钮
  Widget _buildReplyModelSwitchBtn() {
    return Builder(
      builder: (context) {
        return GestureDetector(
          key: _replyModeSwitchBtnAnchorKey,
          onTap: () {
            // 显示回复切换的Popup弹窗
            if (ReplyModeSelectPopup.isShowing()) {
              ReplyModeSelectPopup.dismiss();
              return;
            }
            // 切换回复模式
            ReplyModeSelectPopup.show(
              _replyModeSwitchBtnAnchorKey,
              context,
              modeList: controller.replyModelList.toList(),
              currentMode: controller.currentReplyMode.value!,
              onChooseReplyModeCallback: (ReplyMode newMode) {
                controller.switchReplyMode(newMode);
              },
            );
          },
          child: Container(
            padding: EdgeInsets.symmetric(vertical: 12.h, horizontal: 14.w),
            decoration: BoxDecoration(
              color: ColorName.white,
              borderRadius: BorderRadius.all(Radius.circular(30.w)),
              border: Border.all(
                color: ColorName.bgAiModelSwitchBorderBtn,
                width: 1.w,
              ),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Obx(() {
                  return
                  // 文字
                  GradientText(
                    colors: [
                      ColorName.aiModelSwitchBtnColor1,
                      ColorName.aiModelSwitchBtnColor2,
                    ],
                    child: Text(
                      controller.currentReplyMode.value?.name ?? "",
                      style: TextStyle(
                        fontSize: 14.sp,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  );
                }),
                SizedBox(width: 8.w),
                // 箭头
                Assets.images.iconModeSwitchArrow.image(
                  width: 15.w,
                  height: 15.w,
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  /// 底部操作按钮
  Widget _buildBottomActionBtn(BuildContext context) {
    // 例子，则显示上传截图按钮
    if (controller.uploadInfo.value == null) {
      return Container(
        width: double.maxFinite,
        margin: EdgeInsets.only(top: 8.h, bottom: 20.h),
        child: _buildUploadScreenshotBtn(context),
      );
    }
    // 生成中，或已有结果，隐藏按钮
    if (controller.isResultGenerating.value || controller.hasScanResult.value) {
      return SizedBox.shrink();
    } else {
      // 上传页或结果页，显示2个按钮，模式切换按钮和获取回复按钮
      return Container(
        width: double.maxFinite,
        margin: EdgeInsets.only(
          left: 16.w,
          top: 8.h,
          right: 16.w,
          bottom: 20.h,
        ),
        child: ActionBtn(
          leftBtn: _buildReplyModelSwitchBtn(),
          spaceWidget: SizedBox(width: 10.w),
          rightBtn: _buildGetReplayBtn(),
        ),
      );
    }
  }

  /// 底部布局
  Widget _buildBottomLayout(BuildContext context) {
    return Obx(() {
      return Column(
        // 高度包裹内容
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 操作按钮
          _buildBottomActionBtn(context),
        ],
      );
    });
  }
}
