import 'dart:async';

import 'package:fis_i18n/i18n.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:flyinsono/architecture/router/index.dart';
import 'package:flyinsono/pages/remedical/vocabulary_entry/widgets/entries_item.dart';
import 'package:flyinsono/views/desktop/real_time_consultation/widgets/horizontal_user_card.dart';
import 'package:flyinsono/views/desktop/real_time_consultation/widgets/simple_Info.dart';
import 'package:fis_ui/base_define/page.dart';
import 'package:fis_common/event/event_type.dart';
import 'package:fis_theme/theme.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:fis_common/helpers/encrypt.dart';

class GroupMembersView extends FStatefulWidget implements FPage {
  @override
  String get pageName => "GroupMembersView";

  GroupMembersView({
    required this.getMembersFunc,
    this.isUserMember = false,
  });
  @override
  FState<FStatefulWidget> createState() {
    return _GroupMembersViewState();
  }

  final bool isUserMember;
  final Future<List<SimpleInfoItem>> Function(String, int) getMembersFunc;
}

class _GroupMembersViewState extends FState<GroupMembersView> {
  final _searchInput = TextEditingController();
  final ScrollController _scrollController = ScrollController();
  int _pageIndex = 1;
  List<SimpleInfoItem> _source = [];
  Timer? _debounceTimer;
  String _searchText = '';

  @override
  void initState() {
    _scrollController.addListener(() async {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        _pageIndex++;
        var newDatas = await widget.getMembersFunc(_searchText, _pageIndex);
        setState(() {
          _source.addAll(newDatas);
        });
      }
    });
    if (_pageIndex == 1 && _source.isEmpty) {
      widget.getMembersFunc(_searchText, _pageIndex).then(
            (newDatas) => setState(
              () {
                _source.addAll(newDatas);
              },
            ),
          );
    }
    super.initState();
  }

  @override
  FWidget build(BuildContext context) {
    return FSimpleDialog(
      clipBehavior: Clip.antiAlias,
      contentPadding: EdgeInsets.all(0),
      insetPadding: EdgeInsets.all(10),
      okString: i18nBook.common.confirm.t,
      cancelString: i18nBook.common.cancel.t,
      isDefault: true,
      onCancel: router.back,
      onOk: () {
        router.back();
      },
      title: FText(
        i18nBook.common.view.t,
        style: TextStyle(color: Colors.white),
      ),
      children: [
        _buildSearchInput(),
        _buildMemberList(),
      ],
    );
  }

  @override
  void dispose() {
    _debounceTimer?.cancel();
    _debounceTimer = null;
    _scrollController.dispose();
    super.dispose();
  }

  FWidget _buildSearchInput() {
    return FContainer(
      height: 45,
      margin: EdgeInsets.symmetric(horizontal: 10, vertical: 10),
      child: FRow(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          FBorderInput(
            controller: _searchInput,
            hintSize: 16,
            contentSize: 16,
            maxLength: 20,
            borderColor: Color.fromARGB(255, 187, 180, 180),
            height: 55,
            hintText: i18nBook.common.search.t,
            onChanged: (v) {
              _onTextChanged(v);
            },
          ),
        ],
      ),
    );
  }

  void _onTextChanged(String newText) {
    _pageIndex = 1;
    _searchText = newText;
    if (_debounceTimer?.isActive ?? false) {
      _debounceTimer?.cancel();
    }
    _debounceTimer = Timer(Duration(milliseconds: 200), () async {
      // 在 200ms 后执行搜索操作
      var source = await widget.getMembersFunc.call(_searchText, _pageIndex);
      setState(() {
        _source = source;
      });
    });
  }

  FWidget _buildMemberList() {
    if (_source.isEmpty) {
      return FContainer(
        width: 500,
        height: 500,
        child: NoDataWidget(),
      );
    }
    return FContainer(
      alignment: Alignment.topCenter,
      width: 500,
      height: 500,
      child: FListView.builder(
        shrinkWrap: true,
        itemCount: _source.length,
        controller: _scrollController,
        itemBuilder: (_, i) {
          var user = _source[i];
          return FHorizontalUserSimpleCard(
            margin: EdgeInsets.only(left: 10, right: 10, top: 5),
            itemInfo: user,
            isSelected: false,
            isRedOnly: true,
            height: 80,
            imageSize: 50,
            isUserHeadImage: widget.isUserMember,
            onTap: (isSelected) {},
          );
        },
      ),
    );
  }
}
