import 'dart:async';

import 'package:fis_i18n/i18n.dart';
import 'package:fis_measure/utils/prompt_box.dart';
import 'package:fis_ui/base_define/page.dart';
import 'package:fis_ui/index.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/router/index.dart';
import 'package:flyinsono/managers/interfaces/remedical.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:get/get.dart';
import 'package:rxdart/rxdart.dart';

class SelectPatientPage extends FStatefulWidget implements FPage {
  final void Function(SimpleInfoItem) onSubmit;

  final Future<bool> Function(String)? onAdd;
  final List<SimpleInfoItem> items;
  final bool isCounsultationPatient;

  SelectPatientPage(
    this.onSubmit,
    this.items, {
    this.onAdd,
    this.isCounsultationPatient = false,
  });
  @override
  String get pageName => 'SelectPatientPage';
  @override
  FState<FStatefulWidget> createState() {
    return _SelectPatientState();
  }
}

class _SelectPatientState extends FState<SelectPatientPage> {
  final remedicalManager = Get.find<IRemedicalManager>();
  final _controller = TextEditingController();
  final ScrollController _scrollController = ScrollController();
  final _focusNode = FocusNode();
  final BehaviorSubject<String> _textSubject = BehaviorSubject<String>();
  Timer? _debounce;
  String _selectedUser = '';
  bool _focus = false;
  List<SimpleInfoItem> _viewItems = [];
  bool _isLoading = false;
  int _currentPage = 2;
  @override
  FWidget build(BuildContext context) {
    return FSafeArea(
      child: FScaffold(
        appBar: FAppBar.simple(
            title: i18nBook.realTimeConsultation.pleaseSelectPatient.t,
            onBackClicked: (() => router.back()),
            actions: [
              FElevatedButton(
                child: FText(i18nBook.common.submit.t),
                style: ButtonStyle(
                  elevation: MaterialStateProperty.all<double>(0),
                ),
                onPressed: () {
                  var simpleInfoItem = _viewItems.firstWhereOrNull(
                      (element) => element.itemCode == _selectedUser);
                  if (simpleInfoItem == null) {
                    PromptBox.toast(i18nBook.common.selectAtLeastOnePatient.t);
                    return;
                  }
                  widget.onSubmit.call(simpleInfoItem);
                },
                businessParent: widget,
                name: 'add',
              )
            ]),
        body: FColumn(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            FContainer(
              margin: EdgeInsets.symmetric(horizontal: 20),
              child: FTextField(
                maxLength: 20,
                maxLines: 1,
                controller: _controller,
                decoration: InputDecoration(
                  hintText: i18nBook.common.searchOrAddPatient.t,
                  contentPadding: EdgeInsets.symmetric(vertical: 2),
                  hintStyle: TextStyle(color: Colors.grey),
                  border: UnderlineInputBorder(
                    borderSide: BorderSide(color: Colors.grey),
                  ),
                  suffix: FElevatedButton(
                    businessParent: widget,
                    name: 'add patient',
                    onPressed: () async {
                      var addResult =
                          await widget.onAdd?.call(_controller.text) ?? false;
                      if (addResult) {
                        var viewItems = await remedicalManager
                            .findSimpleInfoPatients(keyWord: _controller.text);
                        setState(() {
                          _viewItems = viewItems;
                        });
                      }
                    },
                    child: FText(i18nBook.common.add.t),
                  ),
                ),
                onChanged: (value) {
                  _textSubject.add(value);
                },
              ),
            ),
            FExpanded(
              child: FListView.builder(
                shrinkWrap: true,
                controller: _scrollController,
                itemCount: _viewItems.length,
                itemBuilder: ((context, index) {
                  if (index == _viewItems.length) {
                    // 显示加载指示器
                    return Center(
                      child: CircularProgressIndicator(),
                    );
                  }
                  var itemInfo = _viewItems[index];
                  var itemCode = itemInfo.itemCode;
                  return FHorizontalUserSimpleCard(
                    itemInfo: _viewItems[index],
                    margin: EdgeInsets.only(
                        top: 5,
                        left: kIsMobile ? 5 : 20,
                        right: kIsMobile ? 5 : 20),
                    height: 100,
                    isSelected: _selectedUser == itemCode,
                    onTap: (selected) {
                      if (selected) {
                        setState(() {
                          _selectedUser = itemCode;
                        });
                      } else {
                        setState(() {
                          _selectedUser = '';
                        });
                      }
                    },
                  );
                }),
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  void didUpdateWidget(SelectPatientPage oldWidget) {
    super.didUpdateWidget(oldWidget);
  }

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

  @override
  void initState() {
    _focusNode.addListener(() {
      if (_focus != _focusNode.hasFocus) {
        setState(() {
          _focus = _focusNode.hasFocus;
        });
      }
    });
    _viewItems = widget.items;
    _textSubject.stream
        .debounceTime(Duration(milliseconds: 200))
        .listen((event) async {
      var viewItems = await remedicalManager.findSimpleInfoPatients(
          keyWord: _controller.text);
      setState(() {
        _viewItems = viewItems;
      });
    });
    _scrollController.addListener(_scrollListener); // 添加滚动监听器
    super.initState();
  }

  Future<void> _loadData() async {
    var newDatas = await remedicalManager.findSimpleInfoPatients(
      keyWord: _controller.text,
      pageIndex: _currentPage,
      isCounsultationPatient: widget.isCounsultationPatient,
    );
    setState(() {
      _viewItems.addAll(newDatas);
      _isLoading = false;
      _currentPage++;
    });
  }

  void _scrollListener() {
    if (_scrollController.position.pixels ==
        _scrollController.position.maxScrollExtent) {
      // 滑动到了底部
      if (!_isLoading) {
        setState(() {
          _isLoading = true;
        });
        _loadData(); // 加载下一页数据
      }
    }
  }
}
