import 'dart:convert';

import 'package:connectivity/connectivity.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:modal_progress_hud/modal_progress_hud.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:shinewash_employee/api/api.dart';
import 'package:shinewash_employee/models/compete_appointment.dart';
import 'package:shinewash_employee/models/current_appointment.dart';
import 'package:shinewash_employee/models/new_appointment.dart';

import 'appointment.dart';
import 'custom_drawer.dart';

const darkBlue = Color(0xFF265E9E);
const extraDarkBlue = Color(0xFF91B4D8);

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage>
    with SingleTickerProviderStateMixin {
  TabController _tabController;
  DateTime currentBackPressTime;

  List<NewAppointment> na = List<NewAppointment>();
  List<NewAppointmentCoworker> nac = List<NewAppointmentCoworker>();
  List<NewAppointmentServices> nas = List<NewAppointmentServices>();

  List<CurrentAppointment> pa = List<CurrentAppointment>();
  List<CurrentAppointmentCoworker> pac = List<CurrentAppointmentCoworker>();
  List<CurrentAppointmentService> pas = List<CurrentAppointmentService>();

  List<CompleteAppointment> cca = List<CompleteAppointment>();
  List<CompleteAppointmentCoworker> ccac = List<CompleteAppointmentCoworker>();
  List<CompleteAppointmentService> ccas = List<CompleteAppointmentService>();
  //
  var showSpinner = false;
  var showCurrentAppointment;
  var showCompleteAppointment;
  var showCancelAppointment;
  var countPending = 0;
  var countCompete = 0;
  var countCancel = 0;

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

  Future<bool> check() async {
    var connectivityResult = await (Connectivity().checkConnectivity());
    if (connectivityResult == ConnectivityResult.mobile) {
      return true;
    } else if (connectivityResult == ConnectivityResult.wifi) {
      return true;
    }
    return false;
  }

  checkInternetConnection() {
    check().then((intenet) async {
      if (intenet != null && intenet) {
      } else {
        showDialog(
          builder: (context) => AlertDialog(
            title: Text('Internet connection'),
            content: Text('Check your internet connection'),
            actions: <Widget>[
              FlatButton(
                onPressed: () async {
                  Navigator.pop(context);
                  Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) => HomePage(),
                      ));
                },
                child: Text('OK'),
              )
            ],
          ),
          context: context,
        );
      }
    });
  }

  void _handleTabSelection() {
    setState(() {});
  }

  Future<void> getNewAppointmentData() async {
    setState(() {
      showSpinner = true;
    });
    var res = await CallApi().getWithToken('appointments');
    var body = json.decode(res.body);
    var theData = body['data'];
    // print(theData);
    // print('new ${theData[0]['id']}');
    if (theData != null) {
      for (int i = 0; i < theData.length; i++) {
        showCompleteAppointment = theData[i]['appointment_status'];
        if (showCompleteAppointment == 'ACCEPT') {
          for (int j = 0; j <= countCompete; j++) {
            Map<String, dynamic> map = theData[i];
            na.add(NewAppointment.fromJson(map));
          }

          for (int k = 0; k <= countCompete; k++) {
            Map<String, dynamic> map = theData[i]['user'];
            nac.add(NewAppointmentCoworker.fromJson(map));
          }

          for (int l = 0; l <= countCompete; l++) {
            var service = theData[l]['coworker']['service'];
            for (int m = 0; m < service.length; m++) {
              Map<String, dynamic> map = service[m];
              nas.add(NewAppointmentServices.fromJson(map));
              // print('services ${service[m]['service_name']}');
            }
          }
        }
      }
    } else {
      na.length = 0;
    }
    setState(() {
      showSpinner = false;
    });
  }

  Future<void> getCurrentAppointmentData() async {
    var res = await CallApi().getWithToken('appointments');
    var body = json.decode(res.body);
    var theData = body['data'];
    // print('working appointment is $theData');
    if (theData != null) {
      for (int i = 0; i < theData.length; i++) {
        showCurrentAppointment = theData[i]['appointment_status'];
        if (showCurrentAppointment == 'WORKING') {
          for (int j = 0; j <= countPending; j++) {
            Map<String, dynamic> map = theData[i];
            pa.add(CurrentAppointment.fromJson(map));
          }

          for (int k = 0; k <= countPending; k++) {
            Map<String, dynamic> map = theData[i]['user'];
            pac.add(CurrentAppointmentCoworker.fromJson(map));
          }

          for (int l = 0; l <= countPending; l++) {
            var service = theData[l]['coworker']['service'];
            for (int m = 0; m < service.length; m++) {
              Map<String, dynamic> map = service[m];
              pas.add(CurrentAppointmentService.fromJson(map));
            }
          }
        }
      }
    } else {
      pa.length = 0;
    }
  }

  Future<void> getCompleteAppointmentData() async {
    var res = await CallApi().getWithToken('appointments');
    var body = json.decode(res.body);
    var theData = body['data'];
    if (theData != null) {
      for (int i = 0; i < theData.length; i++) {
        showCancelAppointment = theData[i]['appointment_status'];
        if (showCancelAppointment == 'COMPLETE') {
          for (int j = 0; j <= countCancel; j++) {
            Map<String, dynamic> map = theData[i];
            cca.add(CompleteAppointment.fromJson(map));
          }

          for (int k = 0; k <= countCancel; k++) {
            Map<String, dynamic> map = theData[i]['user'];
            ccac.add(CompleteAppointmentCoworker.fromJson(map));
          }

          for (int l = 0; l <= countCancel; l++) {
            var service = theData[l]['coworker']['service'];
            for (int m = 0; m < service.length; m++) {
              Map<String, dynamic> map = service[m];
              ccas.add(CompleteAppointmentService.fromJson(map));
            }
          }
        }
      }
    } else {
      cca.length = 0;
    }
  }

  Future<void> changeStatus(data) async {
    setState(() {
      showSpinner = true;
    });
    var res = await CallApi().postDataWithToken(data, 'change_status');
    var body = json.decode(res.body);
    var theData = body['data'];
    print('body is $theData');
    print('body success is ${body['success']}');
    Navigator.pushReplacement(
        context,
        MaterialPageRoute(
          builder: (context) => HomePage(),
        ));
    setState(() {
      showSpinner = false;
    });
  }

  Future<bool> onWillPop() {
    DateTime now = DateTime.now();
    if (currentBackPressTime == null ||
        now.difference(currentBackPressTime) > Duration(seconds: 2)) {
      currentBackPressTime = now;
      Fluttertoast.showToast(msg: 'Press again to exit');
      return Future.value(false);
    }
    return Future.value(true);
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      child: Scaffold(
        appBar: AppBar(
          elevation: 0,
          backgroundColor: Colors.white,
          centerTitle: true,
          title: Text(
            'Appointment',
            style: TextStyle(
              color: darkBlue,
              fontSize: 18.0,
              fontFamily: 'FivoSansMedium',
            ),
          ),
          leading: Container(),
          actions: [
            IconButton(
              icon: Icon(
                FontAwesomeIcons.bars,
                size: 22,
                color: darkBlue,
              ),
              onPressed: () {
                Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => CustomDrawer(
                        index: 0,
                      ),
                    ));
              },
            )
          ],
          bottom: TabBar(
            labelColor: Theme.of(context).primaryColor,
            unselectedLabelColor: Color(0xFF91B4D8),
            labelStyle: TextStyle(
              color: Theme.of(context).primaryColor,
              fontSize: 18,
              fontFamily: 'FivoSansMedium',
            ),
            unselectedLabelStyle: TextStyle(
              color: Color(0xFF91B4D8),
              fontSize: 16,
              fontFamily: 'FivoSansMedium',
            ),
            indicatorColor: Theme.of(context).primaryColor,
            tabs: [
              Tab(
                text: 'New',
              ),
              Tab(
                text: 'Current',
              ),
              Tab(
                text: 'Past',
              ),
            ],
            controller: _tabController,
          ),
        ),
        body: ModalProgressHUD(
          inAsyncCall: showSpinner,
          child: TabBarView(
            children: [
              //first tab
              Container(
                child: na.length == 0
                    ? Container(
                        height: 100.0,
                        width: MediaQuery.of(context).size.width,
                        child: Center(
                            child: Text(
                          'data not found',
                          style: TextStyle(
                            color: darkBlue,
                            fontSize: 16,
                            fontFamily: 'FivoSansMediumOblique',
                          ),
                        )))
                    : ListView.builder(
                        scrollDirection: Axis.vertical,
                        itemCount: na.length,
                        itemBuilder: (context, index) {
                          NewAppointment newAppointment = na[index];
                          NewAppointmentCoworker newAppointmentCoworker =
                              nac[index];
                          NewAppointmentServices newAppointmentService =
                              nas[index];
                          // List<String> theServices = [];
                          // for (int i = 0; i < nas.length; i++) {
                          //   theServices.add(nas[index].serviceName);
                          // }
                          // print(
                          //     'services are ${newAppointmentService.serviceName}');
                          // print('the services is $theServices');
                          return InkWell(
                            onTap: () {
                              // Navigator.push(
                              //     context,
                              //     MaterialPageRoute(
                              //       builder: (context) => Appointment(
                              //         appoinmentId: newAppointment.id,
                              //         path: 'new',
                              //       ),
                              //     ));
                            },
                            child: Card(
                              margin: EdgeInsets.all(10.0),
                              child: Column(
                                children: [
                                  ListTile(
                                    contentPadding: EdgeInsets.all(10.0),
                                    leading: Container(
                                        padding: EdgeInsets.all(2.0),
                                        decoration: BoxDecoration(
                                            color: Colors.white,
                                            borderRadius: BorderRadius.all(
                                              Radius.circular(7.0),
                                            ),
                                            boxShadow: [
                                              BoxShadow(
                                                color: Colors.black26,
                                                blurRadius: 1.0,
                                                spreadRadius: 1.0,
                                              )
                                            ]),
                                        child: ClipRRect(
                                          borderRadius: BorderRadius.all(
                                            Radius.circular(5.0),
                                          ),
                                          child: Image(
                                            image: NetworkImage(
                                              newAppointmentCoworker.image,
                                            ),
                                            height: 50.0,
                                            width: 50.0,
                                            fit: BoxFit.fill,
                                          ),
                                        )),
                                    title: Text(
                                      newAppointmentCoworker.name,
                                      style: TextStyle(
                                        color: darkBlue,
                                        fontSize: 18,
                                        fontFamily: 'FivoSansMedium',
                                      ),
                                    ),
                                    subtitle: Column(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: [
                                        SizedBox(height: 7.0),
                                        Text(
                                          '${newAppointment.date} - ${newAppointment.time}',
                                          style: TextStyle(
                                            color: extraDarkBlue,
                                            fontSize: 14,
                                            fontFamily: 'FivoSansRegular',
                                          ),
                                        ),
                                        Text(
                                          'service : ${newAppointmentService.serviceName}',
                                          maxLines: 1,
                                          overflow: TextOverflow.ellipsis,
                                          style: TextStyle(
                                            color: extraDarkBlue,
                                            fontSize: 14,
                                            fontFamily: 'FivoSansRegular',
                                          ),
                                        )
                                      ],
                                    ),
                                  ),
                                  Container(
                                    width:
                                        MediaQuery.of(context).size.width / 1.2,
                                    margin: EdgeInsets.only(bottom: 5),
                                    child: RaisedButton(
                                        elevation: 1,
                                        color: Color(0xFFE9F0F7),
                                        onPressed: () {
                                          var body = {
                                            'id': newAppointment.id,
                                            'appointment_status': 'working'
                                          };
                                          changeStatus(body);

                                          // showDialog(
                                          //   builder: (context) => AlertDialog(
                                          //     title: Text('Start working'),
                                          //     content: Text(
                                          //         'Are you sure to complete the appointment'),
                                          //     actions: <Widget>[
                                          //       FlatButton(
                                          //         onPressed: () {
                                          //           Navigator.pop(context);
                                          //         },
                                          //         child: Text('No'),
                                          //       ),
                                          //       FlatButton(
                                          //         onPressed: () {
                                          //           Navigator.pop(context);
                                          //         },
                                          //         child: Text('Yes'),
                                          //       ),
                                          //     ],
                                          //   ),
                                          //   context: context,
                                          // );
                                        },
                                        child: Text(
                                          'Start Working',
                                          style: TextStyle(
                                              color: Color(0xFF91B4D8),
                                              fontSize: 16,
                                              fontFamily: 'FivoSansMedium'),
                                        )),
                                  )
                                ],
                              ),
                            ),
                          );
                        },
                      ),
              ),
              //second tab
              Container(
                child: pa.length == 0
                    ? Container(
                        height: 100.0,
                        width: MediaQuery.of(context).size.width,
                        child: Center(
                            child: Text(
                          'data not found',
                          style: TextStyle(
                            color: darkBlue,
                            fontSize: 16,
                            fontFamily: 'FivoSansMediumOblique',
                          ),
                        )))
                    : ListView.builder(
                        scrollDirection: Axis.vertical,
                        itemCount: pa.length,
                        itemBuilder: (context, index) {
                          CurrentAppointment currentAppointment = pa[index];
                          CurrentAppointmentCoworker
                              currentappointmentdataCoworker = pac[index];
                          CurrentAppointmentService
                              currentappointmentdataService = pas[index];
                          return InkWell(
                            onTap: () {
                              Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                    builder: (context) => Appointment(
                                      appoinmentId: currentAppointment.id,
                                      path: 'current',
                                    ),
                                  ));
                            },
                            child: Card(
                              margin: EdgeInsets.all(10.0),
                              child: ListTile(
                                contentPadding: EdgeInsets.all(10.0),
                                leading: Container(
                                    padding: EdgeInsets.all(2.0),
                                    decoration: BoxDecoration(
                                        color: Colors.white,
                                        borderRadius: BorderRadius.all(
                                          Radius.circular(7.0),
                                        ),
                                        boxShadow: [
                                          BoxShadow(
                                            color: Colors.black26,
                                            blurRadius: 1.0,
                                            spreadRadius: 1.0,
                                          )
                                        ]),
                                    child: ClipRRect(
                                      borderRadius: BorderRadius.all(
                                        Radius.circular(5.0),
                                      ),
                                      child: Image(
                                        image: NetworkImage(
                                          currentappointmentdataCoworker.image,
                                        ),
                                        height: 50.0,
                                        width: 50.0,
                                        fit: BoxFit.fill,
                                      ),
                                    )),
                                title: Text(
                                  currentappointmentdataCoworker.name,
                                  style: TextStyle(
                                    color: darkBlue,
                                    fontSize: 18,
                                    fontFamily: 'FivoSansMedium',
                                  ),
                                ),
                                subtitle: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    SizedBox(height: 7.0),
                                    Text(
                                      '${currentAppointment.date} - ${currentAppointment.time}',
                                      style: TextStyle(
                                        color: extraDarkBlue,
                                        fontSize: 14,
                                        fontFamily: 'FivoSansRegular',
                                      ),
                                    ),
                                    Text(
                                      'service : ${currentappointmentdataService.serviceName}',
                                      maxLines: 1,
                                      overflow: TextOverflow.ellipsis,
                                      style: TextStyle(
                                        color: extraDarkBlue,
                                        fontSize: 14,
                                        fontFamily: 'FivoSansRegular',
                                      ),
                                    )
                                  ],
                                ),
                              ),
                            ),
                          );
                        },
                      ),
              ),
              //third tab
              Container(
                child: cca.length == 0
                    ? Container(
                        height: 100.0,
                        width: MediaQuery.of(context).size.width,
                        child: Center(
                            child: Text(
                          'data not found',
                          style: TextStyle(
                            color: darkBlue,
                            fontSize: 16,
                            fontFamily: 'FivoSansMediumOblique',
                          ),
                        )))
                    : ListView.builder(
                        scrollDirection: Axis.vertical,
                        itemCount: cca.length,
                        itemBuilder: (context, index) {
                          CompleteAppointment completeappointmentdata =
                              cca[index];
                          CompleteAppointmentCoworker
                              completeappointmentdataCoworker = ccac[index];
                          CompleteAppointmentService
                              completeappointmentdataService = ccas[index];
                          return InkWell(
                            onTap: () {
                              Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                    builder: (context) => Appointment(
                                      appoinmentId: completeappointmentdata.id,
                                    ),
                                  ));
                            },
                            child: Card(
                              margin: EdgeInsets.all(10.0),
                              child: ListTile(
                                contentPadding: EdgeInsets.all(10.0),
                                leading: Container(
                                    padding: EdgeInsets.all(2.0),
                                    decoration: BoxDecoration(
                                        color: Colors.white,
                                        borderRadius: BorderRadius.all(
                                          Radius.circular(7.0),
                                        ),
                                        boxShadow: [
                                          BoxShadow(
                                            color: Colors.black26,
                                            blurRadius: 1.0,
                                            spreadRadius: 1.0,
                                          )
                                        ]),
                                    child: ClipRRect(
                                      borderRadius: BorderRadius.all(
                                        Radius.circular(5.0),
                                      ),
                                      child: Image(
                                        image: NetworkImage(
                                          completeappointmentdataCoworker.image,
                                        ),
                                        height: 50.0,
                                        width: 50.0,
                                        fit: BoxFit.fill,
                                      ),
                                    )),
                                title: Text(
                                  completeappointmentdataCoworker.name,
                                  style: TextStyle(
                                    color: darkBlue,
                                    fontSize: 18,
                                    fontFamily: 'FivoSansMedium',
                                  ),
                                ),
                                subtitle: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    SizedBox(height: 7.0),
                                    Text(
                                      '${completeappointmentdata.date} - ${completeappointmentdata.time}',
                                      style: TextStyle(
                                        color: extraDarkBlue,
                                        fontSize: 14,
                                        fontFamily: 'FivoSansRegular',
                                      ),
                                    ),
                                    Text(
                                      'service : ${completeappointmentdataService.serviceName}',
                                      maxLines: 1,
                                      overflow: TextOverflow.ellipsis,
                                      style: TextStyle(
                                        color: extraDarkBlue,
                                        fontSize: 14,
                                        fontFamily: 'FivoSansRegular',
                                      ),
                                    )
                                  ],
                                ),
                              ),
                            ),
                          );
                        },
                      ),
              ),
            ],
            controller: _tabController,
          ),
        ),
      ),
      onWillPop: onWillPop,
    );
  }
}
