import 'package:doctor_app_flutter/config/size_config.dart';
import 'package:doctor_app_flutter/core/enum/view_state.dart';
import 'package:doctor_app_flutter/core/model/charts/app_time_series_chart.dart';
import 'package:doctor_app_flutter/core/model/diabetic_chart/DiabeticType.dart';
import 'package:doctor_app_flutter/core/viewModel/patient_view_model.dart';
import 'package:doctor_app_flutter/core/viewModel/project_view_model.dart';
import 'package:doctor_app_flutter/core/model/patient/patiant_info_model.dart';
import 'package:doctor_app_flutter/screens/base/base_view.dart';
import 'package:doctor_app_flutter/screens/patients/profile/diabetic_chart/line_chart_for_diabetic.dart';
import 'package:doctor_app_flutter/utils/date-utils.dart';
import 'package:doctor_app_flutter/utils/utils.dart';
import 'package:doctor_app_flutter/utils/translations_delegate_base_utils.dart';
import 'package:doctor_app_flutter/widgets/patients/profile/app_bar/patient-profile-app-bar.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/errors/error_message.dart';
import 'package:doctor_app_flutter/widgets/shared/loader/gif_loader_dialog_utils.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import 'diabetic_details_blood_pressurewideget.dart';

class DiabeticChart extends StatefulWidget {
  DiabeticChart({
    Key? key,
  }) : super(key: key);

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

class _DiabeticChartState extends State<DiabeticChart> {
  List<TimeSeriesSales2> timeSeriesData1 = [];

  List<TimeSeriesSales2> timeSeriesData2 = [];
  bool isVidaPlusProject= false;

  List<DiabeticType> diabeticType = [
    DiabeticType(nameAr: "Urine Glucose", nameEn: "Urine Glucose", value: 1),
    DiabeticType(nameAr: "Urine Acet", nameEn: "Urine Acet", value: 2),
    DiabeticType(nameAr: "Blood Glucose", nameEn: "Blood Glucose", value: 3),
    DiabeticType(nameAr: "Blood Glucose(Glucometer)", nameEn: "Blood Glucose(Glucometer)", value: 4)
  ];

  DiabeticType selectedDiabeticType = DiabeticType();

  @override
  Widget build(BuildContext context) {
    final routeArgs = ModalRoute.of(context)!.settings.arguments as Map;
    PatiantInformtion patient = routeArgs['patient'];
    isVidaPlusProject = routeArgs['isVidaPlusProject'];
    ProjectViewModel projectsProvider = Provider.of(context);
    return BaseView<PatientViewModel>(
      onModelReady: (model) async {
        selectedDiabeticType = diabeticType[2];

        await model.getDiabeticChartValues(patient, selectedDiabeticType.value!, isLocalBusy: false, isVidaPlusProject: isVidaPlusProject);
        generateData(model);
      },
      builder: (_, model, w) => AppScaffold(
          baseViewModel: model,
          backgroundColor: Theme.of(context).scaffoldBackgroundColor,
          appBar: PatientProfileAppBar(
            patient,
            isInpatient: true,
          ),
          body: SingleChildScrollView(
            child: Column(
              children: [
                Container(
                  width: MediaQuery.of(context).size.width * 0.7,
                  child: DropdownButtonHideUnderline(
                      child: DropdownButton(
                    dropdownColor: Colors.white,
                    iconEnabledColor: Colors.black,
                    isExpanded: true,
                    value: selectedDiabeticType.value,
                    iconSize: 25,
                    elevation: 16,
                    selectedItemBuilder: (BuildContext context) {
                      return diabeticType.map((item) {
                        return Row(
                          mainAxisSize: MainAxisSize.max,
                          mainAxisAlignment: MainAxisAlignment.end,
                          children: <Widget>[
                            Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Container(
                                    padding: EdgeInsets.all(2),
                                    margin: EdgeInsets.all(2),
                                    decoration: new BoxDecoration(
                                      color: Colors.red[800],
                                      borderRadius: BorderRadius.circular(20),
                                    ),
                                    constraints: BoxConstraints(
                                      minWidth: 20,
                                      minHeight: 20,
                                    ),
                                    child: Center(
                                      child: AppText(
                                        diabeticType.length.toString(),
                                        color: Colors.white,
                                        fontSize: projectsProvider.isArabic ? 10 : 11,
                                        textAlign: TextAlign.center,
                                      ),
                                    )),
                              ],
                            ),
                            AppText(selectedDiabeticType.nameEn!, fontSize: 12, color: Colors.black, fontWeight: FontWeight.bold, textAlign: TextAlign.end),
                          ],
                        );
                      }).toList();
                    },
                    onChanged: (newValue) async {
                      await onChangeFunc(newValue, model, patient);
                      setState(() {});
                    },
                    items: diabeticType.map((item) {
                      return DropdownMenuItem(
                        child: AppText(
                          item.nameEn!,
                          textAlign: TextAlign.left,
                        ),
                        value: item.value,
                      );
                    }).toList(),
                  )),
                ),
                timeSeriesData1.length != 0 || timeSeriesData2.length != 0
                    ? Padding(
                        padding: const EdgeInsets.all(10.0),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            Container(
                              margin: EdgeInsets.symmetric(horizontal: 8),
                              decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(12)),
                              child: LineChartForDiabetic(
                                title: selectedDiabeticType.nameEn!,
                                isOX: false,
                                timeSeries1: timeSeriesData1,
                                // timeSeries2: timeSeriesData2,
                                indexes: timeSeriesData1.length ~/ 5.5,
                              ),
                            ),
                            Container(
                              margin: EdgeInsets.symmetric(horizontal: 8, vertical: 16),
                              padding: EdgeInsets.only(top: 16, right: 18.0, left: 16.0),
                              decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(12)),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  AppText(
                                    TranslationBase.of(context).graphDetails,
                                    fontSize: SizeConfig.textMultiplier! * 2.3,
                                    fontWeight: FontWeight.bold,
                                    fontFamily: 'Poppins',
                                  ),
                                  SizedBox(
                                    height: 8,
                                  ),
                                  DiabeticDetails(
                                    diabeticDetailsList: model.diabeticChartValuesList,
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                      )
                    : Center(child: ErrorMessage(error: TranslationBase.of(context).noItem)),
              ],
            ),
          )),
    );
  }

  generateData(PatientViewModel model) {
    if (model.diabeticChartValuesList.length > 0) {
      model.diabeticChartValuesList.toList().forEach(
        (element) {
          if(element.dateChart == null ) return;
          DateTime elementDate = AppDateUtils.getDateTimeFromServerFormat(element.dateChart!);
          if (element.resultValue!.toInt() != 0)
            timeSeriesData1.add(
              TimeSeriesSales2(
                new DateTime(elementDate.year, elementDate.month, elementDate.day),
                element.resultValue!.toDouble(),
              ),
            );
          if (element.resultValue!.toInt() != 0)
            timeSeriesData2.add(
              TimeSeriesSales2(
                new DateTime(elementDate.year, elementDate.month, elementDate.day),
                element.resultValue!.toDouble(),
              ),
            );
        },
      );
    }
  }

  onChangeFunc(newValue, PatientViewModel model, patient) async {
    GifLoaderDialogUtils.showMyDialog(context);
    setState(() {
      selectedDiabeticType = diabeticType[newValue - 1];
      timeSeriesData1.clear();
      timeSeriesData2.clear();
    });

    await model.getDiabeticChartValues(patient, selectedDiabeticType.value!, isLocalBusy: true, isVidaPlusProject: isVidaPlusProject);
    if (model.state == ViewState.ErrorLocal) {
      Utils.showErrorToast(model.error);
    }
    generateData(model);
    GifLoaderDialogUtils.hideDialog(context);
  }
}
