import 'package:diplomaticquarterapp/models/Appointments/AppoimentAllHistoryResultList.dart';
import 'package:diplomaticquarterapp/pages/MyAppointments/models/AppointmentType.dart';
import 'package:diplomaticquarterapp/pages/MyAppointments/widgets/AppointmentCardView.dart';
import 'package:diplomaticquarterapp/services/appointment_services/GetDoctorsList.dart';
import 'package:diplomaticquarterapp/uitl/app_toast.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart';
import 'package:flutter/material.dart';
import 'package:smart_progress_bar/smart_progress_bar.dart';

class MyAppointments extends StatefulWidget {
  List<AppoitmentAllHistoryResultList> appoList = [];

  List<AppoitmentAllHistoryResultList> bookedAppoList = [];
  List<AppoitmentAllHistoryResultList> confirmedAppoList = [];
  List<AppoitmentAllHistoryResultList> arrivedAppoList = [];

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

class _MyAppointmentsState extends State<MyAppointments>
    with SingleTickerProviderStateMixin {
  TabController _tabController;

  bool isDataLoaded = false;

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

  @override
  Widget build(BuildContext context) {
    return AppScaffold(
      appBarTitle: "My Appointments",
      isShowAppBar: true,
      body: Container(
        child: Column(children: [
          /// this is will not colored with theme data
          TabBar(
            tabs: [
              Tab(text: TranslationBase.of(context).booked),
              Tab(text: TranslationBase.of(context).confirmed),
              Tab(text: TranslationBase.of(context).arrived),
            ],
            controller: _tabController,
          ),
          Divider(
            color: Colors.grey[600],
            thickness: 0.5,
          ),
          Expanded(
            child: new TabBarView(
              physics: NeverScrollableScrollPhysics(),
              children: [
                isDataLoaded ? getBookedAppointments() : Container(),
                isDataLoaded ? getConfirmedAppointments() : Container(),
                isDataLoaded ? getArrivedAppointments() : Container()
              ],
              controller: _tabController,
            ),
          ),
        ]),
      ),
    );
  }

  getPatientAppointmentHistory() {
    DoctorsListService service = new DoctorsListService();
    widget.appoList.clear();
    widget.bookedAppoList.clear();
    widget.confirmedAppoList.clear();
    widget.arrivedAppoList.clear();
    service.getPatientAppointmentHistory(false, context).then((res) {
      print(res['AppoimentAllHistoryResultList'].length);
      if (res['MessageStatus'] == 1) {
        setState(() {
          if (res['AppoimentAllHistoryResultList'].length != 0) {
            res['AppoimentAllHistoryResultList'].forEach((v) {
              widget.appoList
                  .add(new AppoitmentAllHistoryResultList.fromJson(v));
            });
            sortAppointmentList();
            openAppointmentsTab();
            isDataLoaded = true;
          } else {}
        });
      } else {
        AppToast.showErrorToast(message: res['ErrorEndUserMessage']);
      }
    }).catchError((err) {
      print(err);
    }).showProgressBar(text: "Loading", backgroundColor: Colors.blue.withOpacity(0.6));
  }

  bool isConfirmed(AppoitmentAllHistoryResultList appo) {
    return AppointmentType.isConfirmed(appo);
  }

  bool isArrived(AppoitmentAllHistoryResultList appo) {
    return AppointmentType.isArrived(appo);
  }

  bool isBooked(AppoitmentAllHistoryResultList appo) {
    return AppointmentType.isBooked(appo);
  }

  sortAppointmentList() {
    widget.appoList.forEach((v) {
      if (isBooked(v)) {
        widget.bookedAppoList.add(v);
      }

      if (isConfirmed(v)) {
        widget.confirmedAppoList.add(v);
      }

      if (isArrived(v)) {
        widget.arrivedAppoList.add(v);
      }
    });
  }

  openAppointmentsTab() {
    if (widget.bookedAppoList.length != 0) {
      _tabController.animateTo((_tabController.index + 1) % 1);
    } else if (widget.confirmedAppoList.length != 0) {
      _tabController.animateTo((_tabController.index + 1) % 2);
    } else if (widget.arrivedAppoList.length != 0) {
      _tabController.animateTo((_tabController.index + 1) % 3);
      return;
    }
  }

  Widget getBookedAppointments() {
    return Container(
      child: widget.bookedAppoList.length != 0
          ? new ListView.builder(
              itemCount: widget.bookedAppoList.length,
              itemBuilder: (context, i) {
                return AppointmentCard(
                  appo: widget.bookedAppoList[i],
                  onReloadAppointmentHistory: getPatientAppointmentHistory,
                );
              },
            )
          : Container(
              child: Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: <Widget>[
                    Image.asset(
                        "assets/images/new-design/noAppointmentIcon.png"),
                    Container(
                      margin: EdgeInsets.only(top: 10.0),
                      child: Text("No Booked Appointments",
                          style: TextStyle(
                            fontSize: 16.0,
                          )),
                    ),
                  ],
                ),
              ),
            ),
    );
  }

  Widget getConfirmedAppointments() {
    return widget.confirmedAppoList.length != 0
        ? Container(
            child: new ListView.builder(
              itemCount: widget.confirmedAppoList.length,
              itemBuilder: (context, i) {
                return AppointmentCard(
                  appo: widget.confirmedAppoList[i],
                  onReloadAppointmentHistory: getPatientAppointmentHistory,
                );
              },
            ),
          )
        : Container(
            child: Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  Image.asset("assets/images/new-design/noAppointmentIcon.png"),
                  Container(
                    margin: EdgeInsets.only(top: 10.0),
                    child: Text("No Confirmed Appointments",
                        style: TextStyle(
                          fontSize: 16.0,
                        )),
                  ),
                ],
              ),
            ),
          );
  }

  Widget getArrivedAppointments() {
    return widget.arrivedAppoList.length != 0
        ? Container(
            child: new ListView.builder(
              itemCount: widget.arrivedAppoList.length,
              itemBuilder: (context, i) {
                return AppointmentCard(
                  appo: widget.arrivedAppoList[i],
                  onReloadAppointmentHistory: getPatientAppointmentHistory,
                );
              },
            ),
          )
        : Container(
            child: Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  Image.asset("assets/images/new-design/noAppointmentIcon.png"),
                  Container(
                    margin: EdgeInsets.only(top: 10.0),
                    child: Text("No Arrived Appointments",
                        style: TextStyle(
                          fontSize: 16.0,
                        )),
                  ),
                ],
              ),
            ),
          );
  }
}
