import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:yumi/shared/tools/sc_loading_manager.dart';
import 'package:yumi/shared/tools/sc_room_utils.dart';
import 'package:yumi/modules/index/main_route.dart';
import 'package:yumi/app_localizations.dart';
import 'package:yumi/ui_kit/components/appbar/socialchat_appbar.dart';
import 'package:yumi/ui_kit/components/sc_compontent.dart';
import 'package:yumi/ui_kit/components/socialchat_gradient_button.dart';
import 'package:yumi/ui_kit/components/text/sc_text.dart';
import 'package:yumi/ui_kit/theme/socialchat_theme.dart';
import 'package:yumi/app/constants/sc_screen.dart';
import 'package:yumi/app/routes/sc_fluro_navigator.dart';
import 'package:yumi/app/constants/sc_global_config.dart';
import 'package:yumi/app/config/business_logic_strategy.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/room_res.dart';

class SCEditRoomSearchAdminPage extends StatefulWidget {
  @override
  _SCEditRoomSearchAdminPageState createState() =>
      _SCEditRoomSearchAdminPageState();
}

class _SCEditRoomSearchAdminPageState extends State<SCEditRoomSearchAdminPage>
    with SingleTickerProviderStateMixin {
  final TextEditingController _textEditingController = TextEditingController();
  List<SocialChatRoomRes> rooms = [];
  bool canEdit = false;

  BusinessLogicStrategy get _strategy => SCGlobalConfig.businessLogicStrategy;

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Image.asset(
          _strategy.getAdminSearchBackgroundImage('roomSearch'),
          width: ScreenUtil().screenWidth,
          height: 150.w,
          fit: BoxFit.fill,
        ),
        Scaffold(
          backgroundColor: Colors.transparent,
          resizeToAvoidBottomInset: false,
          appBar: SocialChatStandardAppBar(
            title: SCAppLocalizations.of(context)!.roomEditing,
            actions: [],
          ),
          body: SafeArea(
            top: false,
            child: Container(
              margin: EdgeInsetsDirectional.only(top: 15.w),
              width: ScreenUtil().screenWidth,
              height: ScreenUtil().screenHeight,
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadiusDirectional.only(
                  topStart: Radius.circular(35.w),
                ),
              ),
              child: Column(
                children: [
                  SizedBox(height: 10.w),
                  Row(
                    children: <Widget>[
                      SizedBox(width: 10.w),
                      Expanded(
                        child: searchWidget(
                          hint: SCAppLocalizations.of(context)!.enterTheRoomId,
                          controller: _textEditingController,
                          borderColor: _strategy.getAdminSearchInputBorderColor('roomSearch'),
                          textColor: _strategy.getAdminSearchInputTextColor('roomSearch'),
                        ),
                      ),
                      socialchatGradientButton(
                        text: SCAppLocalizations.of(context)!.search,
                        radius: 25,
                        textSize: 14.sp,
                        textColor: _strategy.getAdminSearchButtonTextColor('roomSearch'),
                        gradient: LinearGradient(
                          colors: _strategy.getAdminSearchButtonGradient('roomSearch'),
                          begin: Alignment.centerLeft,
                          end: Alignment.centerRight,
                        ),
                        onPress: () {
                          if (_textEditingController.text.isNotEmpty) {
                            _searchUser();
                          }
                        },
                      ),
                      SizedBox(width: 10.w),
                    ],
                  ),
                  SizedBox(height: 10.w),
                  rooms.isNotEmpty
                      ? Expanded(
                        child: ListView.separated(
                          itemBuilder: (context, i) => buildItem(rooms[i]),
                          itemCount: rooms.length,
                          padding: EdgeInsets.zero,
                          separatorBuilder:
                              (context, i) => Divider(
                                height: height(1),
                                color: SocialChatTheme.dividerColor,
                                indent: width(28), //25+50+10
                                endIndent: width(15),
                              ),
                        ),
                      )
                      : mainEmpty(),
                ],
              ),
            ),
          ),
        ),
      ],
    );
  }

  Widget buildItem(SocialChatRoomRes data) {
    return 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(data.id ?? "", context);
            },
            behavior: HitTestBehavior.opaque,
            child: head(url: data.roomCover ?? "", width: 55.w),
          ),
          SizedBox(width: 2.w),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: <Widget>[
                    // richText(
                    //   txt: data.userNickname ?? "",
                    //   key: (widget as SearchUserList).text,
                    //   highlight: SocialChatTheme.primaryColor,
                    //   defaultColor: Colors.black,
                    // ),
                    Expanded(
                      child: text(
                        data.roomName ?? "",
                        fontSize: 15.sp,
                        textColor: Colors.black,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                    SizedBox(width: 5.w),
                    // dj(data.level.toString()),
                  ],
                ),
                Row(
                  children: [
                    text(
                      "ID:${data.roomAccount}",
                      fontSize: 12.sp,
                      textColor: Colors.black26,
                      fontWeight: FontWeight.w600,
                    ),
                  ],
                ),
              ],
            ),
          ),
          canEdit
              ? GestureDetector(
                child: Container(
                  alignment: AlignmentDirectional.center,
                  width: 20.w,
                  height: 20.w,
                  child: Image.asset(
                    _strategy.getAdminSearchEditIcon('roomSearch'),
                    color: Colors.black,
                  ),
                ),
                onTap: () {
                  SCNavigatorUtils.push(
                    context,
                    "${SCMainRoute.editingUserRoomAdmin}?type=Room&profile=${Uri.encodeComponent(jsonEncode(data.toJson()))}",
                  );
                },
              )
              : Container(),
          SizedBox(width: 5.w),
        ],
      ),
    );
  }

  void _searchUser() async {
    try {
      SCLoadingManager.show();
      rooms.clear();
      rooms = await SCChatRoomRepository().searchRoom(
        _textEditingController.text,
      );
      var userIdentity = await SCAccountRepository().userIdentity(
        userId: rooms.first.userId ?? "",
      );
      if (!(userIdentity.admin ?? false) &&
          !(userIdentity.superAdmin ?? false)) {
        canEdit = true;
      }
      SCLoadingManager.hide();
      setState(() {});
    } catch (e) {
      SCLoadingManager.hide();
    }
  }
}
