import 'dart:async';

import 'package:fis_ui/index.dart';
import 'package:flutter/material.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:flyinsono/architecture/router/index.dart';
import 'package:flyinsono/managers/interfaces/user_info.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:get/get.dart';

class FUserSelect extends FStatefulWidget implements FPage {
  final List<SimpleInfoItem> source;
  final String? selectedUser;
  final void Function(SimpleInfoItem?) onOk;
  final Future<List<SimpleInfoItem>> Function(String, int) getUsers;
  FUserSelect(this.selectedUser, this.source, this.onOk, this.getUsers);

  @override
  FState<FStatefulWidget> createState() {
    return FUserSelectState();
  }

  @override
  String get pageName => 'FUserSelect';
}

class FUserSelectState extends FState<FUserSelect> {
  final userInfoManager = Get.find<IUserInfoManager>();
  final _searchInput = TextEditingController();
  final ScrollController _scrollController = ScrollController();
  String _selectedUser = '';
  List<SimpleInfoItem> _source = [];
  int _pageIndex = 1;
  Timer? _debounceTimer;
  String _searchText = '';

  @override
  void initState() {
    _source = widget.source;
    _selectedUser = widget.selectedUser ?? '';
    _scrollController.addListener(() async {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        _pageIndex++;
        var newDatas = await widget.getUsers(_searchText, _pageIndex);
        setState(() {
          _source.addAll(newDatas);
        });
      }
    });
    super.initState();
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  @override
  FWidget build(BuildContext context) {
    return FSimpleDialog(
      okString: i18nBook.common.confirm.t,
      cancelString: i18nBook.common.cancel.t,
      isDefault: true,
      onCancel: router.back,
      onOk: () {
        router.back();
        widget.onOk.call(_selectedUser == ""
            ? null
            : _source
                .firstWhere((element) => element.itemCode == _selectedUser));
      },
      title: FText(
        i18nBook.common.Select.t,
        style: TextStyle(color: Colors.white),
      ),
      children: [
        _buildSearchInput(),
        _buildUserList(),
      ],
    );
  }

  FWidget _buildUserList() {
    if (_source.isEmpty) {
      return FCenter(
        child: FColumn(
          children: [
            FImage.asset(
              "assets/images/no_data.png",
              width: 500,
              height: 500,
              fit: BoxFit.cover,
            ),
            FText(i18nBook.common.noneDataTip.t),
            const FSizedBox(height: 30)
          ],
        ),
      );
    }
    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: 60, right: 60, top: 5),
            itemInfo: user,
            isSelected: _selectedUser == user.itemCode,
            onTap: (isSelected) {
              if (isSelected) {
                if (_selectedUser != user.itemCode) {
                  setState(() {
                    _selectedUser = user.itemCode;
                  });
                }
              } else {
                if (_selectedUser == user.itemCode) {
                  setState(() {
                    _selectedUser = "";
                  });
                }
              }
            },
          );
        },
      ),
    );
  }

  FWidget _buildSearchInput() {
    return FContainer(
      height: 45,
      margin: EdgeInsets.symmetric(horizontal: 60, 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.getUsers.call(_searchText, _pageIndex);
      setState(() {
        _source = source;
      });
    });
  }
}
