import 'package:fis_i18n/i18n.dart';
import 'package:fis_theme/theme.dart';
import 'package:fis_ui/base_define/page.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_ui/widgets/functional/popup_menu_button.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/router/index.dart';
import 'package:flyinsono/managers/interfaces/entities/classInfo.dart';
import 'package:flyinsono/pages/college/controller.dart';
import 'package:flyinsono/pages/college/widgets/my_class/add_user.dart';
import 'package:flyinsono/pages/college/widgets/my_class/apply_review_mobile.dart';
import 'package:flyinsono/pages/college/widgets/my_class/join_class.dart';
import 'package:flyinsono/pages/remedical/consultation/widgets/fcustom_flat_button.dart';
import 'package:flyinsono/pages/remote_controller/index.dart';
import 'package:get/get.dart';

import 'create_class.dart';
import 'custom_card.dart';

class MyClassMobile extends FStatefulWidget implements FPage {
  @override
  FState<FStatefulWidget> createState() {
    return MyClassMobileState();
  }

  @override
  String get pageName => "MyClassMobile";
}

class MyClassMobileState extends FState<MyClassMobile> {
  final serachInput = TextEditingController();
  final controller = Get.find<FlyinsonoCollegeController>();
  final popupMenuButtonTextStyle =
      TextStyle(color: FTheme.ins.colorScheme.primary);

  ///按钮间分割线高度
  static const double _buttonSplitLineHeight = 25;
  ScrollController _scrollController = ScrollController();
  int _selectedIndex = 0;
  bool _tableLoading = false;
  bool _hasReachedEnd = false;
  int _currentPageIndex = 1;
  int _totalItemCount = 0;
  ClassRoleType _currentClassRoleType = ClassRoleType.Teacher;
  @override
  void initState() {
    _initCourseInfos();
    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
              _scrollController.position.maxScrollExtent &&
          controller.state.classInfos.length < _totalItemCount) {
        _currentPageIndex++;
        _getClassInfos(_currentClassRoleType, true); // 加载下一页数据
      }
      if (_scrollController.position.pixels ==
              _scrollController.position.maxScrollExtent &&
          controller.state.classInfos.length == _totalItemCount) {
        _hasReachedEnd = true;
        setState(() {});
      } else {
        _hasReachedEnd = false;
        setState(() {});
      }
    });
    super.initState();
  }

  @override
  FWidget build(BuildContext context) {
    return FScaffold(
      appBar: FAppBar(
        title: FisBuilder<FlyinsonoCollegeController>(
          id: 'class_tabs',
          builder: (_) {
            return _buildTitle();
          },
        ),
        centerTitle: true,
        leading: _buildLeading(),
        actions: [
          FPopupMenuButton<String>(
            itemBuilder: (BuildContext context) => <PopupMenuItem<String>>[
              PopupMenuItem<String>(
                value: "A",
                child: FText(
                  _selectedIndex == 0
                      ? i18nBook.college.createClass.t
                      : i18nBook.college.joinClass.t,
                ),
              ),
            ],
            onSelected: (value) {
              switch (value) {
                case "A":
                  if (_selectedIndex == 0) {
                    router.dialog(
                      () => CreateClass((v) async {
                        var result = await controller.createClass(v);
                        if (result) {
                          router.back();
                        }
                        await controller.createClass(v);
                        setState(() {});
                      }),
                    );
                  } else {
                    router.dialog(
                      () => JoinClass((v) async {
                        bool result = await controller.joinClass(v);
                        if (result) {
                          router.back();
                          setState(() {});
                        }
                      }),
                    );
                  }
                  break;
              }
            },
          ),
        ],
        elevation: 0,
      ),
      body: FColumn(
        children: [
          _buildTopSearchInput(),
          _buildClassInfoCards(),
          if (_hasReachedEnd)
            FContainer(
              height: 30,
              child: FCenter(
                child: FText(
                  i18nBook.remedical.noMore.t,
                  style: TextStyle(
                    fontSize: 14,
                    color: Colors.grey,
                  ),
                ),
              ),
            )
        ],
      ),
    );
  }

  //返回键
  FWidget _buildLeading() {
    return FIconButton(
      name: "back",
      businessParent: this.widget,
      icon: FIcon(Icons.arrow_back_ios_new, size: 20, color: Colors.white),
      onPressed: () {
        Get.back();
      },
    );
  }

  FWidget _buildTitle() {
    return FRow(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        FTextButton(
          name: "teacherRole",
          businessParent: widget,
          onPressed: () => _changeTab(0),
          child: FText(
            i18nBook.college.teacherRole.t,
            style: TextStyle(
              fontSize: 16,
              color: _selectedIndex == 0 ? Colors.black54 : Colors.white,
            ),
          ),
        ),
        FTextButton(
          name: "studentRole",
          businessParent: widget,
          onPressed: () => _changeTab(1),
          child: FText(
            i18nBook.college.studentRole.t,
            style: TextStyle(
              fontSize: 16,
              color: _selectedIndex == 1 ? Colors.black54 : Colors.white,
            ),
          ),
        ),
      ],
    );
  }

  Future<void> _initCourseInfos() async {
    _tableLoading = true;
    _totalItemCount = await controller.getClassInfos(
      roleType: _currentClassRoleType,
      isMobileAndNoNeedPagination: false,
    );
    _tableLoading = false;
    if (mounted) {
      setState(() {});
    }
  }

  void _getClassInfoList() {
    _currentPageIndex = 1;
    if (_selectedIndex == 0) {
      _currentClassRoleType = ClassRoleType.Teacher;
      _getClassInfos(
        _currentClassRoleType,
        false,
      );
    } else {
      _currentClassRoleType = ClassRoleType.Student;
      _getClassInfos(
        _currentClassRoleType,
        false,
      );
    }
  }

  void _getClassInfos(
    ClassRoleType roleType,
    bool isMobileAndNoNeedPagination,
  ) async {
    _tableLoading = true;
    _totalItemCount = await controller.getClassInfos(
      roleType: roleType,
      pageIndex: _currentPageIndex,
      keyword: serachInput.text,
      isMobileAndNoNeedPagination: isMobileAndNoNeedPagination,
    );
    _tableLoading = false;
  }

  void _changeTab(int currentIndex) {
    if (_selectedIndex != currentIndex) {
      _selectedIndex = currentIndex;
      serachInput.text = '';
      _getClassInfoList();
    } else {
      return;
    }
  }

  FWidget _buildTopSearchInput() {
    return FContainer(
      height: 50,
      padding: EdgeInsets.symmetric(vertical: 5),
      child: FBorderInput(
        controller: serachInput,
        fillColor: Colors.white,
        hintSize: 14,
        contentSize: 14,
        maxLength: 50,
        width: double.infinity,
        borderColor: Color.fromARGB(255, 185, 184, 184),
        suffixIcon: FIconButton(
          name: "search",
          onPressed: () {
            _getClassInfoList();
          },
          icon: FIcon(
            Icons.search,
            size: 16,
          ),
          businessParent: this.widget,
        ),
        height: 40,
        margin: EdgeInsets.symmetric(horizontal: 15),
        hintText: i18nBook.common.search.t,
      ),
    );
  }

  FWidget _buildClassInfoCards() {
    return FExpanded(
      child: FObx(
        () => FListView(
          padding: EdgeInsets.symmetric(horizontal: 15),
          shrinkWrap: true,
          controller: _scrollController,
          children: controller.state.classInfos
              .map(
                (info) => FCustomCard(
                  title: info.name!,
                  line2: FTitleField(
                    _selectedIndex == 0
                        ? i18nBook.college.classCode.t
                        : i18nBook.college.relatedCourse.t,
                    FText(
                      _selectedIndex == 0
                          ? info.code!
                          : info.courseCount.toString(),
                      style: TextStyle(color: Colors.black54),
                    ),
                    isBold: false,
                    sizeBetween: 20,
                    titleColor: Colors.black54,
                  ),
                  line3: FTitleField(
                    _selectedIndex == 0
                        ? i18nBook.college.numberOfStudents.t
                        : i18nBook.college.completedExercise.t,
                    FText(
                      _selectedIndex == 0
                          ? info.studentCount.toString()
                          : "0/${info.practiceCount}",
                      style: TextStyle(color: Colors.black54),
                    ),
                    isBold: false,
                    titleColor: Colors.black54,
                    sizeBetween: 20,
                  ),
                  line4: FTitleField(
                    _selectedIndex == 0
                        ? i18nBook.college.bindCourse.t
                        : i18nBook.college.participatedExam.t,
                    FText(
                      _selectedIndex == 0
                          ? info.courseCount.toString()
                          : "0/${info.examCount}",
                      style: TextStyle(color: Colors.black54),
                    ),
                    isBold: false,
                    titleColor: Colors.black54,
                    sizeBetween: 20,
                  ),
                  operateButtons: _selectedIndex == 0
                      ? _buildTeachOperateButtons(info.code!)
                      : _buildStudentOperateButtons(info.code!),
                ),
              )
              .toList(),
        ),
      ),
    );
  }

  FWidget _buildStudentOperateButtons(String code) {
    return FRow(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        FCustomFlatButton(
          i18nBook.college.exercise.t,
          () {},
          businessParent: widget,
          fontColor: FTheme.ins.colorScheme.primary,
        ),
        _getButtonSplitLine(),
        FCustomFlatButton(
          i18nBook.college.exam.t,
          () {},
          businessParent: widget,
          fontColor: FTheme.ins.colorScheme.primary,
        ),
        _getButtonSplitLine(),
        FCustomFlatButton(
          i18nBook.college.quitClass.t,
          () {
            controller.quitClass(code);
          },
          businessParent: widget,
          fontColor: FTheme.ins.colorScheme.primary,
        ),
      ],
    );
  }

  ///按钮间分割线
  FWidget _getButtonSplitLine() {
    return FContainer(
      height: _buttonSplitLineHeight,
      child: FVerticalDivider(
        width: 1,
        thickness: 1,
        color: FTheme.ins.colorScheme.line,
      ),
    );
  }

  FWidget _buildTeachOperateButtons(String code) {
    return FRow(
      children: [
        FCustomFlatButton(
          i18nBook.college.applyForReview.t,
          () async {
            await controller.getApplyStudents(code);
            Get.to(() => ApplayReviewMobile(
                  userGroupCode: code,
                ));
          },
          businessParent: widget,
          fontColor: FTheme.ins.colorScheme.primary,
        ),
        _getButtonSplitLine(),
        FCustomFlatButton(
          i18nBook.college.viewStudent.t,
          () async {
            await controller.getClassStudents(code);
            Get.to(() => ApplayReviewMobile(
                  isApplyReview: false,
                  userGroupCode: code,
                ));
          },
          businessParent: widget,
          fontColor: FTheme.ins.colorScheme.primary,
        ),
        _getButtonSplitLine(),
        FCustomFlatButton(
          i18nBook.college.addStudent.t,
          () {
            Get.to(() => AddClassUser(
                  userGroupCode: code,
                ));
          },
          businessParent: widget,
          fontColor: FTheme.ins.colorScheme.primary,
        ),
        _getButtonSplitLine(),
        FExpanded(
          child: _buildMoreExtendButtons(),
        ),
      ],
    );
  }

  FWidget _buildMoreExtendButtons() {
    return FPopupMenuButton<String>(
      icon: FText(
        i18nBook.measure.expandGroup.t,
        style: TextStyle(
          color: FTheme.ins.colorScheme.primary,
        ),
      ),
      itemBuilder: (BuildContext context) => <PopupMenuItem<String>>[
        /// 暂时屏蔽
        // PopupMenuItem<String>(
        //   value: "1",
        //   child: FText(
        //     i18nBook.college.addTeacher.t,
        //     style: popupMenuButtonTextStyle,
        //   ),
        // ),
        // PopupMenuItem<String>(
        //   value: "2",
        //   child: FText(
        //     i18nBook.college.assignCourse.t,
        //     style: popupMenuButtonTextStyle,
        //   ),
        // ),
        // PopupMenuItem<String>(
        //   value: "3",
        //   child: FText(
        //     i18nBook.college.distributeExam.t,
        //     style: popupMenuButtonTextStyle,
        //   ),
        // ),
        // PopupMenuItem<String>(
        //   value: "4",
        //   child: FText(
        //     i18nBook.college.distributeExercise.t,
        //     style: popupMenuButtonTextStyle,
        //   ),
        // ),
      ],
      onSelected: (value) {
        switch (value) {
          case "1":
            Get.to(AddClassUser(
              isAddStudent: false,
              userGroupCode: 'info.code!',
            ));
            break;
          case "2":
            break;
          case "3":
            break;
          case "4":
            break;
        }
      },
    );
  }
}
