import 'package:charts_flutter/flutter.dart' as charts;
import 'package:diplomaticquarterapp/models/SmartWatch/YearlyStepsResModel.dart';
import 'package:diplomaticquarterapp/services/appointment_services/GetDoctorsList.dart';
import 'package:diplomaticquarterapp/uitl/gif_loader_dialog_utils.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/widgets/charts/app_time_series_chart.dart';
import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart';
import 'package:flutter/material.dart';

class StepsTracker extends StatefulWidget {
  @override
  _StepsTrackerState createState() => _StepsTrackerState();
}

class _StepsTrackerState extends State<StepsTracker>
    with SingleTickerProviderStateMixin {
  TabController _tabController;

  int weeklyStatsAvgValue = 0;
  int monthlyStatsAvgValue = 0;
  int yearlyStatsAvgValue = 0;

  int avgStepsValue = 0;
  int dataLength = 0;

  List<YearlyStepsResModel> yearlyStepsList = List();

  List<TimeSeriesSales> yearlyTimeSeriesData = [];

  bool isDataLoaded = false;

  @override
  void initState() {
    _tabController = new TabController(length: 3, vsync: this);
    WidgetsBinding.instance.addPostFrameCallback((_) {
      getYearlyStepsData();
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return AppScaffold(
      isShowAppBar: true,
      appBarTitle: "Steps",
      isShowDecPage: false,
      body: Container(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            TabBar(
              tabs: [
                Tab(text: TranslationBase.of(context).weekly),
                Tab(text: TranslationBase.of(context).monthly),
                Tab(text: TranslationBase.of(context).yearly),
              ],
              controller: _tabController,
            ),
            Expanded(
              child: new TabBarView(
                physics: NeverScrollableScrollPhysics(),
                children: [
                  isDataLoaded ? getWeeklyStepsDetails() : Container(),
                  isDataLoaded ? getMonthlyStepsDetails() : Container(),
                  isDataLoaded ? getYearlyStepsDetails() : Container()
                ],
                controller: _tabController,
              ),
            ),
          ],
        ),
      ),
    );
  }

  getYearlyStepsData() {
    avgStepsValue = 0;
    dataLength = 0;

    DoctorsListService service = new DoctorsListService();
    GifLoaderDialogUtils.showMyDialog(context);
    service.getPatientHealthDataStats(6, 3, context).then((res) {
      GifLoaderDialogUtils.hideDialog(context);
      print(res['Med_GetYearStepsTransactionsStsList']);
      yearlyStepsList.clear();
      res['Med_GetYearStepsTransactionsStsList'].forEach((element) {
        print('in forEach');
        yearlyStepsList.add(new YearlyStepsResModel.fromJson(element));
        if (element['ValueSum'] != null) {
          double value = element['ValueSum'];
          avgStepsValue += value.toInt();
          dataLength++;
        }
      });
      print("innnnnnnnnnnnnnnnn");
      print(avgStepsValue);
      print(dataLength);
      setState(() {
        yearlyStatsAvgValue = avgStepsValue ~/ dataLength;
        isDataLoaded = true;
      });
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      // AppToast.showErrorToast(message: err);
      print(err);
    });
  }

  generateData() {
    if (yearlyStepsList.length > 0) {
      yearlyTimeSeriesData.clear();
      yearlyStepsList.forEach(
        (element) {
          yearlyTimeSeriesData.add(
            TimeSeriesSales(
              new DateTime(element.year, element.month, 1),
              element.valueSum != null ? element.valueSum.toInt() : 0,
            ),
          );
        },
      );
      yearlyTimeSeriesData.forEach((element) {
        print(element.sales);
        print(element.time);
      });
    }
    return [
      new charts.Series<TimeSeriesSales, DateTime>(
        id: 'Sales',
        colorFn: (_, __) => charts.MaterialPalette.red.shadeDefault,
        domainFn: (TimeSeriesSales sales, _) => sales.time,
        measureFn: (TimeSeriesSales sales, _) => sales.sales,
        data: yearlyTimeSeriesData,
      )
    ];
  }

  getWeeklyStepsDetails() {
    return Container(
      child: Text("Weekly"),
    );
  }

  getMonthlyStepsDetails() {
    return Container(
      child: Text("Monthly"),
    );
  }

  getYearlyStepsDetails() {
    return Container(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
            child: AppTimeSeriesChart(
              seriesList: generateData(),
              chartName: "Steps",
              startDate: DateTime(
                  yearlyStepsList[0].year, yearlyStepsList[0].month, 1),
              endDate: DateTime(
                  yearlyStepsList[yearlyStepsList.length - 1].year,
                  yearlyStepsList[yearlyStepsList.length - 1].month,
                  1),
            ),
          ),
          Container(
            margin: EdgeInsets.only(top: 5.0),
            child: Card(
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(10),
                  side: BorderSide(color: Colors.grey[400], width: 0.6)),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Container(
                    padding: EdgeInsets.fromLTRB(30.0, 15.0, 30.0, 15.0),
                    child:
                        Text("Average Steps", style: TextStyle(fontSize: 18.0)),
                  ),
                  Container(
                    margin: EdgeInsets.only(bottom: 10.0),
                    child: Text(yearlyStatsAvgValue.toString() + " Steps",
                        style: TextStyle(
                            fontSize: 20.0, fontWeight: FontWeight.bold)),
                  ),
                ],
              ),
            ),
          ),
          Container(
            margin: EdgeInsets.all(10.0),
            child: Divider(
              color: Colors.grey[500],
            ),
          ),
          Container(
            transform: Matrix4.translationValues(0.0, -10.0, 0.0),
            margin: EdgeInsets.fromLTRB(20.0, 0.0, 20.0, 5.0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text("History", style: TextStyle(fontSize: 14.0)),
                Row(
                  children: [
                    Text("view more", style: TextStyle(fontSize: 14.0)),
                    Container(
                      margin: EdgeInsets.only(left: 3.0, right: 3.0),
                      transform: Matrix4.translationValues(0.0, 1.5, 0.0),
                      width: 30.0,
                      height: 30.0,
                      child: Image.asset(
                          "assets/images/new-design/view_more.png",
                          fit: BoxFit.contain),
                    ),
                  ],
                ),
              ],
            ),
          ),
          Container(
            margin: EdgeInsets.fromLTRB(20.0, 0.0, 20.0, 5.0),
            child: Card(
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(10),
                  side: BorderSide(color: Colors.grey[400], width: 0.6)),
              child: Row(
                mainAxisSize: MainAxisSize.max,
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Container(
                    padding: EdgeInsets.fromLTRB(30.0, 15.0, 30.0, 15.0),
                    child: Text("Date",
                        style: TextStyle(
                            fontSize: 18.0, fontWeight: FontWeight.bold)),
                  ),
                  Container(
                    padding: EdgeInsets.fromLTRB(30.0, 0.0, 30.0, 0.0),
                    child: Text("Steps", style: TextStyle(fontSize: 18.0)),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}
