import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_debouncer/flutter_debouncer.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:yumi/app_localizations.dart';
import 'package:yumi/app/config/business_logic_strategy.dart';
import 'package:yumi/ui_kit/components/sc_compontent.dart';
import 'package:yumi/ui_kit/components/text/sc_text.dart';
import 'package:yumi/shared/tools/sc_pick_utils.dart';
import 'package:yumi/shared/data_sources/sources/local/user_manager.dart';
import 'package:yumi/shared/data_sources/sources/repositories/sc_room_repository_imp.dart';
import 'package:yumi/shared/data_sources/sources/repositories/sc_user_repository_impl.dart';
import 'package:yumi/shared/business_logic/models/res/login_res.dart';

import 'package:yumi/ui_kit/components/appbar/socialchat_appbar.dart';
import 'package:yumi/ui_kit/components/sc_tts.dart';
import 'package:yumi/app/constants/sc_screen.dart';
import 'package:yumi/app/constants/sc_global_config.dart';
import 'package:yumi/app/routes/sc_fluro_navigator.dart';
import 'package:yumi/shared/tools/sc_room_utils.dart';
import 'package:yumi/shared/business_logic/models/res/room_res.dart';
import 'package:yumi/modules/index/main_route.dart';

class SCEditingUserRoomPage extends StatefulWidget {
  final String type;

  ///被举报的id(用户id或者房间id)
  final SocialChatUserProfile? userProfile;
  final SocialChatRoomRes? roomProfile;

  const SCEditingUserRoomPage({
    Key? key,
    required this.type,
    this.userProfile,
    this.roomProfile,
  }) : super(key: key);

  @override
  _SCEditingUserRoomPageState createState() => _SCEditingUserRoomPageState();
}

class _SCEditingUserRoomPageState extends State<SCEditingUserRoomPage> {
  // 业务逻辑策略访问器
  BusinessLogicStrategy get _strategy => SCGlobalConfig.businessLogicStrategy;

  num selectedIndex = 0;
  String reportReason = "";
  List<String> imageUrls = []; // 动态图片URL列表

  int violationType = 1;
  final TextEditingController _descriptionController = TextEditingController();
  Debouncer debouncer = Debouncer();

  @override
  void initState() {
    super.initState();
    final violationTypeMapping = _strategy.getAdminEditingViolationTypeMapping(widget.type);
    if (violationTypeMapping.isNotEmpty) {
      // 获取第一个值作为默认违规类型
      violationType = violationTypeMapping.values.first;
    }
    // 初始化图片URL列表，长度为最大上传数量
    final maxImageCount = _strategy.getAdminEditingMaxImageUploadCount();
    imageUrls = List.generate(maxImageCount, (index) => '');
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Image.asset(
          _strategy.getAdminEditingBackgroundImage(),
          width: ScreenUtil().screenWidth,
          height: ScreenUtil().screenHeight,
          fit: BoxFit.fill,
        ),
        Scaffold(
          backgroundColor: Colors.transparent,
          resizeToAvoidBottomInset: false,
          appBar: SocialChatStandardAppBar(
            actions: [],
            title:
                widget.type == "User"
                    ? SCAppLocalizations.of(context)!.userEditing
                    : SCAppLocalizations.of(context)!.roomEditing,
            backgroundColor: Colors.transparent,
          ),
          body: SafeArea(
            top: false,
            child: SingleChildScrollView(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  widget.type == "User"
                      ? Container(
                        padding: EdgeInsets.symmetric(
                          vertical: 8.w,
                          horizontal: 5.w,
                        ),
                        margin: EdgeInsets.symmetric(horizontal: 15.w),
                        decoration: BoxDecoration(
                          color: Colors.white,
                          border: Border.all(color: Colors.black12, width: 1.w),
                          borderRadius: BorderRadius.all(Radius.circular(12.w)),
                        ),
                        child: Row(
                          children: [
                            GestureDetector(
                              onTap: () {
                                SCNavigatorUtils.push(
                                  context,
                                  "${SCMainRoute.person}?isMe=${AccountStorage().getCurrentUser()?.userProfile?.id == widget.userProfile?.id}&tageId=${widget.userProfile?.id}",
                                );
                              },
                              behavior: HitTestBehavior.opaque,
                              child: head(
                                url: widget.userProfile?.userAvatar ?? "",
                                width: 55.w,
                              ),
                            ),
                            SizedBox(width: 2.w),
                            Expanded(
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Row(
                                    children: <Widget>[
                                      xb(
                                        widget.userProfile?.userSex,
                                        color:
                                            widget.userProfile?.userSex == 1
                                                ? Colors.blue
                                                : Colors.purpleAccent,
                                      ),
                                      SizedBox(width: 5.w),
                                      // richText(
                                      //   txt: data.userNickname ?? "",
                                      //   key: (widget as SearchUserList).text,
                                      //   highlight: SocialChatTheme.primaryColor,
                                      //   defaultColor: Colors.black,
                                      // ),
                                      Expanded(
                                        child: text(
                                          widget.userProfile?.userNickname ??
                                              "",
                                          fontSize: 15.sp,
                                          fontWeight: FontWeight.w600,
                                          textColor: Colors.black,
                                        ),
                                      ),
                                      SizedBox(width: 5.w),
                                      // dj(data.level.toString()),
                                    ],
                                  ),
                                  Row(
                                    children: [
                                      GestureDetector(
                                        child: Container(
                                          padding: EdgeInsets.symmetric(
                                            vertical: 8.w,
                                          ),
                                          decoration: BoxDecoration(
                                            image: DecorationImage(
                                              image: AssetImage(
                                                (widget.userProfile
                                                            ?.hasSpecialId() ??
                                                        false)
                                                    ? _strategy.getAdminEditingIcon('specialIdBg')
                                                    : _strategy.getAdminEditingIcon('normalIdBg'),
                                              ),
                                              fit: BoxFit.fitWidth,
                                            ),
                                          ),
                                          child: Row(
                                            textDirection: TextDirection.ltr,
                                            children: [
                                              SizedBox(width: 38.w),
                                              text(
                                                widget.userProfile?.getID() ??
                                                    "",
                                                fontSize: 12.sp,
                                                textColor: Colors.white,
                                                fontWeight: FontWeight.bold,
                                              ),
                                              SizedBox(width: 5.w),
                                              Image.asset(
                                                _strategy.getAdminEditingIcon('copyId'),
                                                width: 12.w,
                                                height: 12.w,
                                              ),
                                              SizedBox(width: 8.w),
                                            ],
                                          ),
                                        ),
                                        onTap: () {
                                          Clipboard.setData(
                                            ClipboardData(
                                              text:
                                                  widget.userProfile?.getID() ??
                                                  "",
                                            ),
                                          );
                                          SCTts.show(
                                            SCAppLocalizations.of(
                                              context,
                                            )!.copiedToClipboard,
                                          );
                                        },
                                      ),
                                    ],
                                  ),
                                ],
                              ),
                            ),
                            SizedBox(width: 5.w),
                          ],
                        ),
                      )
                      : Container(
                        padding: EdgeInsets.symmetric(
                          vertical: 8.w,
                          horizontal: 5.w,
                        ),
                        margin: EdgeInsets.symmetric(horizontal: 15.w),
                        decoration: BoxDecoration(
                          color: Colors.white,
                          border: Border.all(color: Colors.black12, width: 1.w),
                          borderRadius: BorderRadius.all(Radius.circular(12.w)),
                        ),
                        child: Row(
                          children: [
                            GestureDetector(
                              onTap: () {
                                SCRoomUtils.goRoom(
                                  widget.roomProfile?.id ?? "",
                                  context,
                                );
                              },
                              behavior: HitTestBehavior.opaque,
                              child: head(
                                url: widget.roomProfile?.roomCover ?? "",
                                width: 55.w,
                              ),
                            ),
                            SizedBox(width: 2.w),
                            Expanded(
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Row(
                                    children: <Widget>[
                                      Expanded(
                                        child: text(
                                          widget.roomProfile?.roomName ?? "",
                                          fontSize: 15.sp,
                                          fontWeight: FontWeight.w600,
                                          textColor: Colors.black,
                                        ),
                                      ),
                                      SizedBox(width: 5.w),
                                      // dj(data.level.toString()),
                                    ],
                                  ),
                                  Row(
                                    children: [
                                      GestureDetector(
                                        child: Container(
                                          padding: EdgeInsets.symmetric(
                                            vertical: 8.w,
                                          ),
                                          child: Row(
                                            textDirection: TextDirection.ltr,
                                            children: [
                                              SizedBox(width: 5.w),
                                              text(
                                                "ID:${widget.roomProfile?.roomAccount}",
                                                fontSize: 12.sp,
                                                textColor: Colors.black26,
                                                fontWeight: FontWeight.bold,
                                              ),
                                              SizedBox(width: 5.w),
                                              Image.asset(
                                                _strategy.getAdminEditingIcon('copyId'),
                                                width: 12.w,
                                                height: 12.w,
                                                color: Colors.black26,
                                              ),
                                              SizedBox(width: 8.w),
                                            ],
                                          ),
                                        ),
                                        onTap: () {
                                          Clipboard.setData(
                                            ClipboardData(
                                              text:
                                                  widget
                                                      .roomProfile
                                                      ?.roomAccount ??
                                                  "",
                                            ),
                                          );
                                          SCTts.show(
                                            SCAppLocalizations.of(
                                              context,
                                            )!.copiedToClipboard,
                                          );
                                        },
                                      ),
                                    ],
                                  ),
                                ],
                              ),
                            ),
                            SizedBox(width: 5.w),
                          ],
                        ),
                      ),
                  SizedBox(height: 10.w),
                  Row(
                    children: [
                      SizedBox(width: 15.w),
                      text(
                        SCAppLocalizations.of(
                          context,
                        )!.pleaseSelectTheTypeToProcess,
                        fontSize: 14.sp,
                        fontWeight: FontWeight.w600,
                        textColor: Colors.black,
                      ),
                      SizedBox(width: 15.w),
                    ],
                  ),
                  Container(
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(12),
                      color: Colors.white,
                      border: Border.all(color: Color(0xffE6E6E6), width: 1.w),
                    ),
                    margin: EdgeInsets.only(top: 10.w, left: 15.w, right: 15.w),
                    padding: EdgeInsets.symmetric(horizontal: 15.w),
                    child: Column(
                      children: [
                        // 动态生成违规类型选项
                        ..._buildViolationTypeOptions(context),
                        SizedBox(height: 20.w,),
                        Row(
                          children: [
                            text(
                              SCAppLocalizations.of(context)!.description,
                              fontSize: 14.sp,
                              fontWeight: FontWeight.w500,
                              textColor: Colors.black,
                            ),
                            Spacer(),
                          ],
                        ),
                        SizedBox(height: 8.w),
                        Container(
                          padding: EdgeInsets.all(5.w),
                          decoration: _strategy.getAdminEditingInputDecoration(),
                          child: TextField(
                            controller: _descriptionController,
                            onChanged: (text) {},
                            maxLength: _strategy.getAdminEditingDescriptionMaxLength(),
                            maxLines: 5,
                            decoration: InputDecoration(
                              hintText:
                                  SCAppLocalizations.of(context)!.inputDesHint,
                              hintStyle: TextStyle(
                                color: Colors.black45,
                                fontSize: 14.sp,
                              ),
                              contentPadding: EdgeInsets.only(top: 0.w),

                              isDense: true,
                              filled: false,
                              focusColor: Colors.transparent,
                              hoverColor: Colors.transparent,
                              border: InputBorder.none,
                              enabledBorder: InputBorder.none,
                              focusedBorder: InputBorder.none,
                              disabledBorder: InputBorder.none,
                              errorBorder: InputBorder.none,
                              focusedErrorBorder: InputBorder.none,
                              // enabledBorder: UnderlineInputBorder(
                              //   borderSide: BorderSide(width: 0.5,color: Colors.white,style: BorderStyle.solid),),
                              // focusedBorder: UnderlineInputBorder(
                              //   borderSide: BorderSide(width: 0.5,color: Colors.white,style: BorderStyle.solid),),
                              // prefixIcon: Padding(padding: EdgeInsets.all(8.w), child: Image.asset("images/login/sc_icon_phone.png",width: 20.w, height: 20.w,fit: BoxFit.fill,),),
                              fillColor: Colors.black45,
                            ),
                            style: TextStyle(
                              fontSize: sp(15),
                              color: Colors.black,
                              textBaseline: TextBaseline.alphabetic,
                            ),
                          ),
                        ),
                        SizedBox(height: 5.w),
                        Row(
                          children: [
                            text(
                              SCAppLocalizations.of(context)!.screenshotTips,
                              fontSize: 14.sp,
                              textColor: Colors.black,
                              fontWeight: FontWeight.w500,
                            ),
                            Spacer(),
                          ],
                        ),
                        SizedBox(height: 8.w),
                        Row(
                          children: [
                            // 动态生成图片上传组件
                            ...List.generate(_strategy.getAdminEditingMaxImageUploadCount(), (index) {
                              return Expanded(
                                child: GestureDetector(
                                  child: Stack(
                                    children: [
                                      imageUrls[index].isNotEmpty
                                          ? netImage(url: imageUrls[index], height: 100.w)
                                          : Image.asset(
                                            _strategy.getAdminEditingIcon('addPic'),
                                            height: 100.w,
                                          ),
                                      imageUrls[index].isNotEmpty
                                          ? Positioned(
                                            top: 5.w,
                                            right: 5.w,
                                            child: GestureDetector(
                                              child: Image.asset(
                                                _strategy.getAdminEditingIcon('closePic'),
                                                width: 14.w,
                                                height: 14.w,
                                              ),
                                              onTap: () {
                                                setState(() {
                                                  imageUrls[index] = "";
                                                });
                                              },
                                            ),
                                          )
                                          : Container(),
                                    ],
                                  ),
                                  onTap: () {
                                    SCPickUtils.pickImage(context, (
                                      bool success,
                                      String url,
                                    ) {
                                      if (success) {
                                        setState(() {
                                          imageUrls[index] = url;
                                        });
                                      }
                                    });
                                  },
                                ),
                              );
                            }).expand((widget) => [widget, if (_strategy.getAdminEditingMaxImageUploadCount() > 1 && widget != Expanded) SizedBox(width: 5.w)]).toList(),
                          ],
                        ),
                        SizedBox(height: 15.w),
                      ],
                    ),
                  ),
                  SizedBox(height: 45.w),
                  GestureDetector(
                    behavior: HitTestBehavior.opaque,
                    onTap: () {
                      debouncer.debounce(
                        duration: Duration(milliseconds: 350),
                        onDebounce: () {
                          List<String> uploadedImages = imageUrls.where((url) => url.isNotEmpty).toList();
                          if (widget.type == "User") {
                             SCAccountRepository().userViolationHandle(
                              widget.userProfile?.id ?? "",
                              violationType,
                              1,
                              _descriptionController.text,
                              imageUrls: imageUrls,
                            ).then((b){
                               SCTts.show(SCAppLocalizations.of(context)!.operationSuccessful);
                               SCNavigatorUtils.goBack(context);
                             }).catchError((e){

                             });
                          } else {
                             SCChatRoomRepository().roomViolationHandle(
                              widget.roomProfile?.id ?? "",
                              violationType,
                              1,
                              _descriptionController.text,
                              imageUrls: imageUrls,
                            ).then((b){
                               SCTts.show(SCAppLocalizations.of(context)!.operationSuccessful);
                               SCNavigatorUtils.goBack(context);
                             }).catchError((e){

                             });
                          }
                        },
                      );
                    },
                    child: Container(
                      height: 40.w,
                      width: double.infinity,
                      alignment: Alignment.center,
                      margin: EdgeInsets.symmetric(horizontal: 45.w),
                      decoration: BoxDecoration(
                        gradient: LinearGradient(
                          begin: AlignmentDirectional.topCenter,
                          end: AlignmentDirectional.bottomCenter,
                          colors: _strategy.getAdminEditingButtonGradient('warning'),
                        ),
                        borderRadius: BorderRadius.circular(25.w),
                      ),
                      child: Text(
                        SCAppLocalizations.of(context)!.warning,
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 16.sp,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    ),
                  ),
                  SizedBox(height: 20.w),
                  GestureDetector(
                    behavior: HitTestBehavior.opaque,
                    onTap: () {
                      debouncer.debounce(
                        duration: Duration(milliseconds: 350),
                        onDebounce: () {
                          List<String> uploadedImages = imageUrls.where((url) => url.isNotEmpty).toList();
                          if (widget.type == "User") {
                             SCAccountRepository().userViolationHandle(
                              widget.userProfile?.id ?? "",
                              violationType,
                              2,
                              _descriptionController.text,
                              imageUrls: imageUrls,
                            ).then((b){
                              SCTts.show(SCAppLocalizations.of(context)!.operationSuccessful);
                              SCNavigatorUtils.goBack(context);
                             }).catchError((e){

                             });
                          } else {
                             SCChatRoomRepository().roomViolationHandle(
                              widget.roomProfile?.id ?? "",
                              violationType,
                              2,
                              _descriptionController.text,
                              imageUrls: imageUrls,
                            ).then((b){
                               SCTts.show(SCAppLocalizations.of(context)!.operationSuccessful);
                               SCNavigatorUtils.goBack(context);
                             }).catchError((e){

                             });
                          }
                        },
                      );
                    },
                    child: Container(
                      height: 40.w,
                      width: double.infinity,
                      alignment: Alignment.center,
                      margin: EdgeInsets.symmetric(horizontal: 45.w),
                      decoration: BoxDecoration(
                        gradient: LinearGradient(
                          begin: AlignmentDirectional.topCenter,
                          end: AlignmentDirectional.bottomCenter,
                          colors: _strategy.getAdminEditingButtonGradient('adjust'),
                        ),
                        borderRadius: BorderRadius.circular(25.w),
                      ),
                      child: Text(
                        SCAppLocalizations.of(context)!.adjust,
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 16.sp,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    ),
                  ),
                  SizedBox(height: 35.w),
                ],
              ),
            ),
          ),
        ),
      ],
    );
  }

  List<Widget> _buildViolationTypeOptions(BuildContext context) {
    final violationTypeMapping = _strategy.getAdminEditingViolationTypeMapping(widget.type);
    final List<Widget> options = [];

    if (violationTypeMapping.isEmpty) {
      // 如果没有映射，返回默认选项
      if (widget.type == "User") {
        options.add(_item(SCAppLocalizations.of(context)!.userName, 0, 1));
        options.add(_item(SCAppLocalizations.of(context)!.userProfilePicture, 1, 2));
      } else {
        options.add(_item(SCAppLocalizations.of(context)!.roomName, 0, 3));
        options.add(_item(SCAppLocalizations.of(context)!.roomProfilePicture, 1, 4));
        options.add(_item(SCAppLocalizations.of(context)!.roomNotice, 2, 5));
        options.add(_item(SCAppLocalizations.of(context)!.roomTheme, 3, 6));
      }
      return options;
    }

    // 根据映射动态生成选项
    int index = 0;
    violationTypeMapping.forEach((displayName, typeId) {
      // 需要将英文显示名称转换为本地化文本
      String localizedName;
      switch (displayName) {
        case 'Pornography':
          localizedName = SCAppLocalizations.of(context)!.pornography;
          break;
        case 'Illegal information':
          localizedName = SCAppLocalizations.of(context)!.illegalInformation;
          break;
        case 'Fraud':
          localizedName = SCAppLocalizations.of(context)!.fraud;
          break;
        case 'Other':
          localizedName = SCAppLocalizations.of(context)!.others;
          break;
        case 'User Name':
          localizedName = SCAppLocalizations.of(context)!.userName;
          break;
        case 'User Profile Picture':
          localizedName = SCAppLocalizations.of(context)!.userProfilePicture;
          break;
        case 'Room Name':
          localizedName = SCAppLocalizations.of(context)!.roomName;
          break;
        case 'Room Profile Picture':
          localizedName = SCAppLocalizations.of(context)!.roomProfilePicture;
          break;
        case 'Room Notice':
          localizedName = SCAppLocalizations.of(context)!.roomNotice;
          break;
        case 'Room Theme':
          localizedName = SCAppLocalizations.of(context)!.roomTheme;
          break;
        default:
          localizedName = displayName;
      }
      options.add(_item(localizedName, index, typeId));
      index++;
    });

    return options;
  }

  Widget _item(String str, int index, int vtype) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () {
        setState(() {
          reportReason = str;
          selectedIndex = index;
          violationType = vtype;
        });
      },
      child: Container(
        width: double.infinity,
        height: 35.w,
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            text(str, fontSize: 13.sp, textColor: Colors.black,fontWeight: FontWeight.w500),
            Spacer(),
            selectedIndex == index
                ? Image.asset(
                  _strategy.getAdminEditingIcon('checked'),
                  width: 20.w,
                  fit: BoxFit.fitWidth,
                )
                : Container(
                  width: 20.w,
                  height: 20.w,
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    border: Border.all(color: Colors.grey, width: 2.w),
                  ),
                ),
          ],
        ),
      ),
    );
  }
}
