import 'package:diplomaticquarterapp/config/shared_pref_kay.dart';
import 'package:diplomaticquarterapp/models/Appointments/DoctorListResponse.dart';
import 'package:diplomaticquarterapp/models/Appointments/DoctorProfile.dart';
import 'package:diplomaticquarterapp/models/Authentication/authenticated_user.dart';
import 'package:diplomaticquarterapp/routes.dart';
import 'package:diplomaticquarterapp/uitl/app_shared_preferences.dart';
import 'package:diplomaticquarterapp/uitl/app_toast.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/widgets/dialogs/confirm_dialog.dart';
import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart';
import 'package:flutter/material.dart';
import 'package:rating_bar/rating_bar.dart';
import 'package:diplomaticquarterapp/services/robo_search/event_provider.dart';
import 'BookConfirm.dart';
import 'components/DocAvailableAppointments.dart';
import 'components/DocInfo.dart';

class DoctorProfile extends StatefulWidget {
  DoctorList doctor;
  DoctorProfileList docProfileList;
  final bool isOpenAppt;
  DoctorProfile(
      {@required this.doctor,
      @required this.docProfileList,
      this.isOpenAppt = false});

  AuthenticatedUser authUser;

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

class _DoctorProfileState extends State<DoctorProfile>
    with TickerProviderStateMixin {
  TabController _tabController;
  bool showFooterButton = false;
  var event = RobotProvider();
  @override
  void initState() {
    _tabController = new TabController(
        length: 2,
        vsync: this,
        initialIndex: widget.isOpenAppt == true ? 1 : 0);

    event.controller.stream.listen((p) {
      if (p['clinic_id'] != null &&
          p['doctor_id'] != null &&
          p['project_id'] != null) {
        setState(() {
          // need to take the data from here
          // dropdownValue = p['clinic_id'];
        });
      }
    });
    _tabController = new TabController(length: 2, vsync: this);
    widget.authUser = new AuthenticatedUser();
    getPatientData();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return AppScaffold(
      appBarTitle: TranslationBase.of(context).bookAppo,
      isShowAppBar: true,
      bottomSheet: showFooterButton
          ? Container(
              width: MediaQuery.of(context).size.width,
              height: 50.0,
              margin: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
              child: ButtonTheme(
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(10.0),
                ),
                minWidth: MediaQuery.of(context).size.width * 0.7,
                height: 45.0,
                child: RaisedButton(
                  color: new Color(0xFF60686b),
                  textColor: Colors.white,
                  disabledTextColor: Colors.white,
                  disabledColor: new Color(0xFFbcc2c4),
                  onPressed: goToBookConfirm,
                  child: Text(TranslationBase.of(context).bookNow,
                      style: TextStyle(fontSize: 18.0)),
                ),
              ),
            )
          : null,
      body: Container(
        color: new Color(0xFFf6f6f6),
        child: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Container(
                color: Colors.white,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Container(
                      margin: EdgeInsets.only(top: 20.0),
                      alignment: Alignment.center,
                      child: ClipRRect(
                        borderRadius: BorderRadius.circular(100.0),
                        child: Image.network(widget.doctor.doctorImageURL,
                            fit: BoxFit.fill, height: 120.0, width: 120.0),
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.only(top: 10.0),
                      alignment: Alignment.center,
                      child: Text(
                          widget.doctor.doctorTitle + " " + widget.doctor.name,
                          textAlign: TextAlign.center,
                          style: TextStyle(
                              fontSize: 20.0,
                              color: Colors.grey[900],
                              letterSpacing: 1.0)),
                    ),
                    Container(
                      margin: EdgeInsets.only(top: 10.0),
                      alignment: Alignment.center,
                      child: Text(widget.doctor.clinicName,
                          style: TextStyle(
                              fontSize: 13.0,
                              color: Colors.grey[900],
                              letterSpacing: 1.0)),
                    ),
                    Container(
                      margin: EdgeInsets.only(top: 5.0),
                      alignment: Alignment.center,
                      child: RatingBar.readOnly(
                        initialRating:
                            widget.doctor.actualDoctorRate.toDouble(),
                        size: 35.0,
                        filledColor: Colors.yellow[700],
                        emptyColor: Colors.grey[500],
                        isHalfAllowed: true,
                        halfFilledIcon: Icons.star_half,
                        filledIcon: Icons.star,
                        emptyIcon: Icons.star,
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.only(top: 5.0),
                      alignment: Alignment.center,
                      child: Text(
                          "(" +
                              widget.doctor.noOfPatientsRate.toString() +
                              " Reviews)",
                          style: TextStyle(
                            fontSize: 14.0,
                            color: Colors.blue[800],
                            letterSpacing: 1.0,
                            decoration: TextDecoration.underline,
                          )),
                    ),
                    Container(
                      margin: EdgeInsets.only(top: 10.0),
                      child: Divider(
                        color: Colors.grey[500],
                      ),
                    ),
                    TabBar(
                      onTap: (index) {
                        setState(() {
                          index == 1
                              ? showFooterButton = true
                              : showFooterButton = false;
                          print(showFooterButton);
                        });
                      },
                      tabs: [
                        Tab(
                            child: Text(TranslationBase.of(context).docInfo,
                                style: TextStyle(color: Colors.black))),
                        Tab(
                          child: Text(TranslationBase.of(context).availableAppo,
                              style: TextStyle(color: Colors.black)),
                        )
                      ],
                      controller: _tabController,
                    ),
                  ],
                ),
              ),
              Container(
                height: MediaQuery.of(context).size.height,
                child: TabBarView(
                  physics: NeverScrollableScrollPhysics(),
                  children: [
                    DoctorInformation(docProfileList: widget.docProfileList),
                    DocAvailableAppointments(doctor: widget.doctor)
                  ],
                  controller: _tabController,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  getPatientData() async {
    AppSharedPreferences sharedPref = AppSharedPreferences();
    if (await sharedPref.getObject(USER_PROFILE) != null) {
      var data =
          AuthenticatedUser.fromJson(await sharedPref.getObject(USER_PROFILE));
      setState(() {
        print(data);
        widget.authUser = data;
      });
    }
  }

  void goToBookConfirm() {
    if (DocAvailableAppointments.areSlotsAvailable) {
      if (widget.authUser.patientID != null) {
        navigateToBookConfirm(context);
      } else {
        ConfirmDialog dialog = new ConfirmDialog(
            context: context,
            confirmMessage: "You have to login to use this service",
            okText: TranslationBase.of(context).confirm,
            cancelText: TranslationBase.of(context).cancel_nocaps,
            okFunction: () => {navigateToLogin()},
            cancelFunction: () => {});
        dialog.showAlertDialog(context);
      }
    } else
      AppToast.showErrorToast(message: "Please select Time Slot to continue");
  }

  navigateToLogin() {
    ConfirmDialog.closeAlertDialog(context);
    Navigator.of(context).pushNamed(
      WELCOME_LOGIN,
    );
  }

  Future navigateToBookConfirm(context) async {
    Navigator.push(
        context,
        MaterialPageRoute(
            builder: (context) => BookConfirm(
                doctor: widget.doctor,
                selectedDate: DocAvailableAppointments.selectedDate,
                selectedTime: DocAvailableAppointments.selectedTime)));
  }
}
