import 'package:doctor_app_flutter/config/size_config.dart';
import 'package:doctor_app_flutter/core/enum/viewstate.dart';
import 'package:doctor_app_flutter/core/model/patient_muse/PatientSearchRequestModel.dart';
import 'package:doctor_app_flutter/core/viewModel/PatientSearchViewModel.dart';
import 'package:doctor_app_flutter/core/viewModel/project_view_model.dart';
import 'package:doctor_app_flutter/models/dashboard/get_special_clinical_care_List_Respose_Model.dart';
import 'package:doctor_app_flutter/screens/base/base_view.dart';
import 'package:doctor_app_flutter/screens/patients/In_patient/InPatientHeader.dart';
import 'package:doctor_app_flutter/util/dr_app_toast_msg.dart';
import 'package:doctor_app_flutter/util/helpers.dart';
import 'package:doctor_app_flutter/util/translations_delegate_base.dart';
import 'package:doctor_app_flutter/widgets/shared/app_scaffold_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/app_texts_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/loader/gif_loader_dialog_utils.dart';
import 'package:doctor_app_flutter/widgets/shared/text_fields/text_fields_utils.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import '../DischargedPatientPage.dart';
import 'in_patient_list_page.dart';

class InPatientScreen extends StatefulWidget {
  GetSpecialClinicalCareListResponseModel specialClinic;

  bool isAllClinic = true;
  bool showBottomSheet = false;
  String selectedClinicName;
  InPatientScreen({Key? key, this.specialClinic});

  @override
  _InPatientScreenState createState() => _InPatientScreenState();
}

class _InPatientScreenState extends State<InPatientScreen>
    with SingleTickerProviderStateMixin {
  TabController _tabController;
  int _activeTab = 0;
  int selectedMapId;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 3, vsync: this);
    _tabController.addListener(_handleTabSelection);
  }

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

  _handleTabSelection() {
    Helpers.hideKeyboard(context);
    setState(() {
      widget.showBottomSheet = false;
      _activeTab = _tabController.index;
    });
  }

  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    PatientSearchRequestModel requestModel = PatientSearchRequestModel();
    ProjectViewModel projectsProvider = Provider.of<ProjectViewModel>(context);

    return BaseView<PatientSearchViewModel>(
      onModelReady: (model) async {
        model.clearPatientList();
        if (widget.specialClinic != null) {
          await model
              .getSpecialClinicalCareMappingList(widget.specialClinic.clinicID);
          // requestModel.nursingStationID =
          //     model.specialClinicalCareMappingList[0].nursingStationID;
        }
        requestModel.clinicID = 0;
        await model.getInPatientList(requestModel);
      },
      builder: (_, model, w) => AppScaffold(
        baseViewModel: model,
        isShowAppBar: true,
        appBar: InPatientHeader(
            model: model,
            selectedMapId: selectedMapId,
            specialClinic: widget.specialClinic,
            activeTab: _activeTab,
            onChangeFunc: (newValue) async {
              setState(() {
                selectedMapId = newValue;
              });
              model.clearPatientList();
              GifLoaderDialogUtils.showMyDialog(context);

              PatientSearchRequestModel requestModel =
                  PatientSearchRequestModel(
                      nursingStationID: selectedMapId, clinicID: 0);
              await model.getInPatientList(requestModel, isLocalBusy: true);
              GifLoaderDialogUtils.hideDialog(context);
              if (model.state == ViewState.ErrorLocal) {
                DrAppToastMsg.showErrorToast(model.error);
              } else {
                onChangeState(
                    isAllClinic: true,
                    showBottomSheet: false,
                    selectedClinicName: null);
              }
            }),
        body: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Expanded(
              child: Scaffold(
                extendBodyBehindAppBar: false,
                appBar: PreferredSize(
                  preferredSize: Size.fromHeight(
                      MediaQuery.of(context).size.height * 0.070),
                  child: Container(
                    height: MediaQuery.of(context).size.height * 0.070,
                    decoration: BoxDecoration(
                        border: Border(
                          bottom: BorderSide(
                              color: Theme.of(context).dividerColor,
                              width: 0.5), //width: 0.7
                        ),
                        color: Colors.white),
                    child: Center(
                      child: TabBar(
                        isScrollable: false,
                        controller: _tabController,
                        indicatorColor: Colors.transparent,
                        indicatorWeight: 1.0,
                        indicatorSize: TabBarIndicatorSize.tab,
                        labelColor: Theme.of(context).primaryColor,
                        labelPadding: EdgeInsets.only(
                            top: 0, left: 0, right: 0, bottom: 0),
                        unselectedLabelColor: Colors.grey[800],
                        tabs: [
                          tabWidget(screenSize, _activeTab == 0,
                              TranslationBase.of(context).inPatientAll,
                              counter: model.inPatientList.length),
                          tabWidget(screenSize, _activeTab == 1,
                              TranslationBase.of(context).myInPatientTitle,
                              counter: model.myIinPatientList.length),
                          tabWidget(screenSize, _activeTab == 2,
                              TranslationBase.of(context).discharged),
                        ],
                      ),
                    ),
                  ),
                ),
                body: Column(
                  children: [
                    Expanded(
                      child: TabBarView(
                        physics: BouncingScrollPhysics(),
                        controller: _tabController,
                        children: [
                          InPatientListPage(
                              isMyInPatient: false,
                              patientSearchViewModel: model,
                              isAllClinic: widget.isAllClinic,
                              showBottomSheet: widget.showBottomSheet,
                              selectedClinicName: widget.selectedClinicName,
                              onChangeValue: onChangeState),
                          InPatientListPage(
                              isMyInPatient: true,
                              patientSearchViewModel: model,
                              isAllClinic: widget.isAllClinic,
                              showBottomSheet: widget.showBottomSheet,
                              selectedClinicName: widget.selectedClinicName,
                              onChangeValue: onChangeState),
                          DischargedPatient(),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  onChangeState({isAllClinic, showBottomSheet, selectedClinicName}) {
    setState(() {
      widget.isAllClinic = isAllClinic;
      widget.showBottomSheet = showBottomSheet;
      widget.selectedClinicName = selectedClinicName;
    });
  }

  Widget tabWidget(Size screenSize, bool isActive, String title,
      {int counter = -1}) {
    return Center(
      child: Container(
        height: screenSize.height * 0.070,
        decoration: TextFieldsUtils.containerBorderDecoration(
            isActive ? Color(0xFFD02127 /*B8382B*/) : Color(0xFFEAEAEA),
            isActive ? Color(0xFFD02127) : Color(0xFFEAEAEA),
            borderRadius: 4,
            borderWidth: 0),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            AppText(
              title,
              fontSize: SizeConfig.textMultiplier * 1.5,
              color: isActive ? Colors.white : Color(0xFF2B353E),
              fontWeight: FontWeight.w700,
            ),
            if (counter != -1)
              Container(
                margin: EdgeInsets.all(4),
                width: 15,
                height: 15,
                decoration: BoxDecoration(
                  color: isActive ? Colors.white : Color(0xFFD02127),
                  shape: BoxShape.circle,
                ),
                child: Center(
                  child: FittedBox(
                    child: AppText(
                      "$counter",
                      fontSize: SizeConfig.textMultiplier * 1.5,
                      color: !isActive ? Colors.white : Color(0xFFD02127),
                      fontWeight: FontWeight.w700,
                    ),
                  ),
                ),
              ),
          ],
        ),
      ),
    );
  }
}
