import 'dart:convert';

import 'package:connectivity/connectivity.dart';
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:modal_progress_hud/modal_progress_hud.dart';
import 'package:shinewash_employee/api/api.dart';
import 'package:shinewash_employee/models/completed.dart';
import 'package:shinewash_employee/models/ongoing.dart';

import 'appointment.dart';

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

class AppointmentProcess extends StatefulWidget {
  // final int selectIndex;
  // const AppointmentProcess({Key key, this.selectIndex}) : super(key: key);
  @override
  _AppointmentProcessState createState() => _AppointmentProcessState();
}

class _AppointmentProcessState extends State<AppointmentProcess>
    with SingleTickerProviderStateMixin {
  TabController _tabController;
  var showSpinner = false;
  bool _isLoggedIn;
  var onGoing;
  var completed;
  var countPending = 0;
  var countCompete = 0;
  var countCancel = 0;
  // int selectIndex;

  List<OnGoing> og = List<OnGoing>();
  List<OnGoingCoworker> ogc = List<OnGoingCoworker>();
  List<OnGoingServices> ogs = List<OnGoingServices>();

  List<Completed> co = List<Completed>();
  List<CompletedCoworker> coc = List<CompletedCoworker>();
  List<CompletedServices> cos = List<CompletedServices>();
  @override
  void initState() {
    super.initState();
    checkInternetConnection();
    _tabController = TabController(length: 2, vsync: this);
    _tabController.addListener(_handleTabSelection);
    ongoing();
    completedFun();
    // selectIndex = widget.selectIndex;
  }

  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) => AppointmentProcess(),
                      ));
                },
                child: Text('OK'),
              )
            ],
          ),
          context: context,
        );
      }
    });
  }

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

  Future<void> ongoing() async {
    setState(() {
      showSpinner = true;
    });
    var res = await CallApi().getWithToken('coworker_appointment');
    var body = json.decode(res.body);
    var theData = body['data'];
    // print(theData);
    // print('new ${theData[0]['id']}');
    onGoing = theData['ongoing'];
    for (int i = 0; i < onGoing.length; i++) {
      // print('ongoing is ${theData['ongoing']}');
      for (int j = 0; j <= countCompete; j++) {
        Map<String, dynamic> map = onGoing[i];
        og.add(OnGoing.fromJson(map));
      }

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

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

  Future<void> completedFun() async {
    setState(() {
      showSpinner = true;
    });
    var res = await CallApi().getWithToken('coworker_appointment');
    var body = json.decode(res.body);
    var theData = body['data'];
    // print(theData);
    // print('new ${theData[0]['id']}');
    completed = theData['past'];
    for (int i = 0; i < completed.length; i++) {
      // print('ongoing is ${theData['ongoing']}');
      for (int j = 0; j <= countCompete; j++) {
        Map<String, dynamic> map = completed[i];
        co.add(Completed.fromJson(map));
      }

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

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

  // Future<void> getPendingAppointmentData() async {
  //   var res = await CallApi().getWithToken('appointment');
  //   var body = json.decode(res.body);
  //   var theData = body['data'];
  //   for (int i = 0; i < theData.length; i++) {
  //     showPendingAppointment = theData[i]['appointment_status'];
  //     if (showPendingAppointment == 'PENDING') {
  //       for (int j = 0; j <= countPending; j++) {
  //         Map<String, dynamic> map = theData[i];
  //         pa.add(PendingAppointment.fromJson(map));
  //       }
  //
  //       for (int k = 0; k <= countPending; k++) {
  //         Map<String, dynamic> map = theData[i]['coworker'];
  //         pac.add(PendingAppointmentCoworker.fromJson(map));
  //       }
  //
  //       for (int l = 0; l <= countPending; l++) {
  //         var service = theData[l]['service'];
  //         for (int m = 0; m < service.length; m++) {
  //           Map<String, dynamic> map = service[m];
  //           pas.add(PendingAppointmentService.fromJson(map));
  //         }
  //       }
  //     }
  //   }
  // }

  // Future<void> getCompleteAppointmentData() async {
  //   var res = await CallApi().getWithToken('appointment');
  //   var body = json.decode(res.body);
  //   var theData = body['data'];
  //   for (int i = 0; i < theData.length; i++) {
  //     showCompleteAppointment = theData[i]['appointment_status'];
  //     if (showCompleteAppointment == 'COMPLETE') {
  //       for (int j = 0; j <= countCompete; j++) {
  //         Map<String, dynamic> map = theData[i];
  //         ca.add(CompleteAppointment.fromJson(map));
  //       }
  //
  //       for (int k = 0; k <= countCompete; k++) {
  //         Map<String, dynamic> map = theData[i]['coworker'];
  //         cac.add(CompleteAppointmentCoworker.fromJson(map));
  //       }
  //
  //       for (int l = 0; l <= countCompete; l++) {
  //         var service = theData[l]['service'];
  //         for (int m = 0; m < service.length; m++) {
  //           Map<String, dynamic> map = service[m];
  //           cas.add(CompleteAppointmentService.fromJson(map));
  //         }
  //       }
  //     }
  //   }
  // }

  // Future<void> getCancelAppointmentData() async {
  //   var res = await CallApi().getWithToken('appointment');
  //   var body = json.decode(res.body);
  //   var theData = body['data'];
  //   for (int i = 0; i < theData.length; i++) {
  //     showCancelAppointment = theData[i]['appointment_status'];
  //     if (showCancelAppointment == 'CANCEL') {
  //       for (int j = 0; j <= countCancel; j++) {
  //         Map<String, dynamic> map = theData[i];
  //         cca.add(CancelAppointment.fromJson(map));
  //       }
  //
  //       for (int k = 0; k <= countCancel; k++) {
  //         Map<String, dynamic> map = theData[i]['coworker'];
  //         ccac.add(CancelAppointmentCoworker.fromJson(map));
  //       }
  //
  //       for (int l = 0; l <= countCancel; l++) {
  //         var service = theData[l]['service'];
  //         for (int m = 0; m < service.length; m++) {
  //           Map<String, dynamic> map = service[m];
  //           ccas.add(CancelAppointmentService.fromJson(map));
  //         }
  //       }
  //     }
  //   }
  // }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        elevation: 0,
        backgroundColor: Colors.white,
        centerTitle: true,
        title: Text(
          'Appointment',
          style: TextStyle(
            color: darkBlue,
            fontSize: 18.0,
            fontFamily: 'FivoSansMedium',
          ),
        ),
        leading: IconButton(
          iconSize: 25.0,
          icon: Icon(
            Icons.chevron_left,
            color: darkBlue,
          ),
          onPressed: () {
            Navigator.pop(context);
          },
        ),
        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: 'On Going',
            ),
            Tab(
              text: 'Completed',
            ),
          ],
          controller: _tabController,
        ),
      ),
      body: ModalProgressHUD(
        inAsyncCall: showSpinner,
        child: TabBarView(
          children: [
            Container(
              margin: EdgeInsets.all(15.0),
              child: og.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: og.length,
                      itemBuilder: (context, index) {
                        OnGoing ongoing = og[index];
                        OnGoingCoworker ongoingcoworker = ogc[index];
                        OnGoingServices ongoingservice = ogs[index];
                        return InkWell(
                          onTap: () {
                            Navigator.push(
                                context,
                                MaterialPageRoute(
                                  builder: (context) => Appointment(
                                    appoinmentId: ongoing.id,
                                    path: 'appointmentongoing',
                                    process: 'On Going ...',
                                  ),
                                ));
                          },
                          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(
                                        ongoingcoworker.image,
                                      ),
                                      height: 50.0,
                                      width: 50.0,
                                      fit: BoxFit.fill,
                                    ),
                                  )),
                              title: Text(
                                ongoingcoworker.name,
                                style: TextStyle(
                                  color: darkBlue,
                                  fontSize: 18,
                                  fontFamily: 'FivoSansMedium',
                                ),
                              ),
                              subtitle: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  SizedBox(height: 7.0),
                                  Text(
                                    '${ongoing.date} - ${ongoing.time}',
                                    style: TextStyle(
                                      color: extraDarkBlue,
                                      fontSize: 14,
                                      fontFamily: 'FivoSansRegular',
                                    ),
                                  ),
                                  Text(
                                    'service : ${ongoingservice.serviceName}',
                                    maxLines: 1,
                                    overflow: TextOverflow.ellipsis,
                                    style: TextStyle(
                                      color: extraDarkBlue,
                                      fontSize: 14,
                                      fontFamily: 'FivoSansRegular',
                                    ),
                                  )
                                ],
                              ),
                            ),
                          ),
                        );
                      },
                    ),
            ),
            Container(
              margin: EdgeInsets.all(15.0),
              child: co.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: co.length,
                      itemBuilder: (context, index) {
                        Completed completed = co[index];
                        CompletedCoworker completedcoworker = coc[index];
                        CompletedServices completedservice = cos[index];
                        return InkWell(
                          onTap: () {
                            Navigator.push(
                                context,
                                MaterialPageRoute(
                                  builder: (context) => Appointment(
                                    appoinmentId: completed.id,
                                    path: 'appointmentcompleted',
                                    process: 'Completed',
                                  ),
                                ));
                          },
                          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(
                                        completedcoworker.image,
                                      ),
                                      height: 50.0,
                                      width: 50.0,
                                      fit: BoxFit.fill,
                                    ),
                                  )),
                              title: Text(
                                completedcoworker.name,
                                style: TextStyle(
                                  color: darkBlue,
                                  fontSize: 18,
                                  fontFamily: 'FivoSansMedium',
                                ),
                              ),
                              subtitle: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  SizedBox(height: 7.0),
                                  Text(
                                    '${completed.date} - ${completed.time}',
                                    style: TextStyle(
                                      color: extraDarkBlue,
                                      fontSize: 14,
                                      fontFamily: 'FivoSansRegular',
                                    ),
                                  ),
                                  Text(
                                    'service : ${completedservice.serviceName}',
                                    maxLines: 1,
                                    overflow: TextOverflow.ellipsis,
                                    style: TextStyle(
                                      color: extraDarkBlue,
                                      fontSize: 14,
                                      fontFamily: 'FivoSansRegular',
                                    ),
                                  )
                                ],
                              ),
                            ),
                          ),
                        );
                      },
                    ),
            ),
          ],
          controller: _tabController,
        ),
      ),
    );
  }
}
