import 'package:doctor_app_flutter/core/enum/filter_type.dart';
import 'package:doctor_app_flutter/core/enum/patient_type.dart';
import 'package:doctor_app_flutter/core/enum/view_state.dart';
import 'package:doctor_app_flutter/core/model/patient/patient_model.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/authentication_view_model.dart';
import 'package:doctor_app_flutter/core/viewModel/project_view_model.dart';
import 'package:doctor_app_flutter/icons_app/doctor_app_icons.dart';
import 'package:doctor_app_flutter/routes.dart';
import 'package:doctor_app_flutter/screens/base/base_view.dart';
import 'package:doctor_app_flutter/screens/patients/patient_search/patient_search_header.dart';
import 'package:doctor_app_flutter/utils/tab_utils.dart';
import 'package:doctor_app_flutter/utils/translations_delegate_base_utils.dart';
import 'package:doctor_app_flutter/widgets/patients/patient_card/PatientCard.dart';
import 'package:doctor_app_flutter/widgets/shared/app_scaffold_widget.dart';
import 'package:doctor_app_flutter/widgets/shared/errors/error_message.dart';
import 'package:doctor_app_flutter/widgets/shared/loader/gif_loader_dialog_utils.dart';
import 'package:doctor_app_flutter/widgets/shared/text_fields/app_text_field_custom_serach.dart';
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:provider/provider.dart';

import 'filter_date_page.dart';

// ignore: must_be_immutable
class OutPatientsScreen extends StatefulWidget {
  final patientSearchForm;
  final selectedType;
  final isAppbar;
  final arrivalType;
  final isView;
  final PatientType? selectedPatientType;
  final PatientSearchRequestModel? patientSearchRequestModel;
  final bool isSearchWithKeyInfo;
  final bool isSearch;
  final bool isInpatient;
  final bool isSearchAndOut;
  final String? searchKey;

  OutPatientsScreen(
      {this.patientSearchForm,
      this.selectedType,
      this.isAppbar = true,
      this.arrivalType,
      this.isView,
      this.selectedPatientType,
      this.patientSearchRequestModel,
      this.isSearchWithKeyInfo = true,
      this.isSearch = false,
      this.isInpatient = false,
      this.searchKey,
      this.isSearchAndOut = false});

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

class _OutPatientsScreenState extends State<OutPatientsScreen> {
  int? clinicId;
  late AuthenticationViewModel authenticationViewModel;

  List<String> _times = [];

  int _activeLocation = 1;
  String patientType = '';
  String patientTypeTitlem = '';
  var selectedFilter = 1;
  String arrivalType = '';
  late ProjectViewModel projectsProvider;
  var isView;
  final _controller = TextEditingController();

  PatientModel patient = PatientModel();

  OutPatientFilterType outPatientFilterType = OutPatientFilterType.Today;
  bool isSortDes = true;

  @override
  Widget build(BuildContext context) {
    authenticationViewModel = Provider.of(context);
    projectsProvider = Provider.of(context);
    _times = [
      TranslationBase.of(context).previous,
      TranslationBase.of(context).today,
      TranslationBase.of(context).nextWeek,
    ];
    final screenSize = MediaQuery.of(context).size;

    return BaseView<PatientSearchViewModel>(
      onModelReady: (model) async {
        await model.getOutPatient(widget.patientSearchRequestModel!);
      },
      builder: (_, model, w) => AppScaffold(
          appBarTitle: "Search Patient",
          isShowAppBar: true,
          appBar: PatientSearchHeader(
            title: TranslationBase.of(context).myOutPatient,
          ),
          baseViewModel: model,
          body: Column(
            children: [
              Container(
                // color: Colors.red,
                height: TabUtils.getTabHeight(context),
                color: TabUtils.getBgTabColor(),
                child: Row(
                  mainAxisSize: MainAxisSize.max,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: _times.map((item) {
                    bool _isActive = _times[_activeLocation] == item ? true : false;

                    return Expanded(
                      child: InkWell(
                        onTap: () async {
                          setState(() {
                            _activeLocation = _times.indexOf(item);
                            outPatientFilterType = _activeLocation == 0
                                ? OutPatientFilterType.Previous
                                : _activeLocation == 1
                                    ? OutPatientFilterType.Today
                                    : OutPatientFilterType.NextWeek;
                            _controller.text = "";
                          });
                          model.searchData("");
                          FocusScope.of(context).requestFocus(new FocusNode());
                          GifLoaderDialogUtils.showMyDialog(context);
                          await model.getPatientBasedOnDate(
                              item: item,
                              selectedPatientType: widget.selectedPatientType,
                              patientSearchRequestModel: widget.patientSearchRequestModel,
                              isSearchWithKeyInfo: widget.isSearchWithKeyInfo,
                              outPatientFilterType: outPatientFilterType);
                          GifLoaderDialogUtils.hideDialog(context);
                        },
                        child: Center(
                          child: Container(
                            height: screenSize.height * 0.070,
                            decoration: TabUtils.getBoxTabsBoxDecoration(
                                isActive: _isActive,
                                isFirst: _times.indexOf(item) == 0,
                                isLast: _times.indexOf(item) == _times.length - 1,
                                isMiddle: _times.indexOf(item) != 0 && _times.indexOf(item) != _times.length - 1,
                                projectViewModel: projectsProvider),
                            child: Center(
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  TabUtils.getTabText(title: item, isActive: _isActive),
                                  _isActive && _activeLocation != 0 && model.state == ViewState.Idle ? TabUtils.getTabCounter(isActive: _isActive, counter: model.filterData.length) : Container(),
                                ],
                              ),
                            ),
                          ),
                        ),
                      ),
                    );
                  }).toList(),
                ),
              ),
              SizedBox(height: 18.5),
              AppTextFieldCustomSearch(
                searchController: _controller,
                onChangeFun: (value) {
                  model.searchData(value);
                },
                marginTop: 5,
                suffixIcon: IconButton(
                  icon: Icon(
                    _activeLocation != 0 ? DoctorApp.filter_1 : FontAwesomeIcons.slidersH.data,
                    color: Colors.black,
                  ),
                  iconSize: 20,
                  onPressed: _activeLocation != 0
                      ? null
                      : () {
                          Navigator.push(
                              context,
                              MaterialPageRoute(
                                builder: (BuildContext context) => FilterDatePage(
                                  outPatientFilterType: outPatientFilterType,
                                  patientSearchViewModel: model,
                                ),
                                settings: RouteSettings(name: 'FilterOutPatentDateScreen'),
                              ));
                        },
                ),
                positionedChild: IconButton(
                  icon: Icon(
                    isSortDes ? FontAwesomeIcons.sortAmountDown.data : FontAwesomeIcons.sortAmountUp.data,
                    color: Colors.black,
                  ),
                  iconSize: 20,
                  onPressed: () {
                    model.sortOutPatient(isDes: isSortDes);
                    isSortDes = !isSortDes;
                  },
                ),
                onFieldSubmitted: () {},
              ),
              Expanded(
                child: Container(
                    child: model.filterData.isEmpty
                        ? Center(
                            child: ErrorMessage(
                              error: TranslationBase.of(context).youDontHaveAnyPatient,
                            ),
                          )
                        : ListView.builder(
                            scrollDirection: Axis.vertical,
                            shrinkWrap: true,
                            itemCount: model.filterData.length,
                            itemBuilder: (BuildContext ctxt, int index) {
                              if (_activeLocation != 0 || (model.filterData[index].patientStatusType != null && model.filterData[index].patientStatusType == 43))
                                return Padding(
                                  padding: EdgeInsets.symmetric(horizontal: 8, vertical: 0),
                                  child: PatientCard(
                                    patientInfo: model.filterData[index],
                                    patientType: patientType,
                                    arrivalType: arrivalType,
                                    isFromSearch: widget.isSearchAndOut,
                                    isInpatient: widget.isInpatient,
                                    onTap: () {
                                      Navigator.of(context).pushNamed(PATIENTS_PROFILE, arguments: {
                                        "patient": model.filterData[index],
                                        "patientType": "1",
                                        "from": widget.patientSearchRequestModel!.from,
                                        "to": widget.patientSearchRequestModel!.from,
                                        "isSearch": false,
                                        "isInpatient": false,
                                        "arrivalType": "7",
                                        "isSearchAndOut": false,
                                        "isSigned": model.filterData[index].isSigned != null ? model.filterData[index].isSigned : false,
                                      });
                                    },
                                    // isFromSearch: widget.isSearch,
                                  ),
                                );
                              else
                                return SizedBox();
                            })),
              ),
            ],
          )),
    );
  }
}
