import 'dart:convert';
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/appointment_view.dart';
import 'package:smooth_star_rating/smooth_star_rating.dart';
import 'custom_drawer.dart';
import 'home_page.dart';

// import 'package:shinewash/api/api.dart';
// import 'package:shinewash/models/view_appoitment_service.dart';
// import 'package:smooth_star_rating/smooth_star_rating.dart';
const darkBlue = Color(0xFF265E9E);
const extraDarkBlue = Color(0xFF91B4D8);
const ratingStar = Color(0xFFFECD03);

class Appointment extends StatefulWidget {
  final appoinmentId;
  final String process;
  final String path;
  Appointment({Key key, this.appoinmentId, this.path, this.process})
      : super(key: key);
  @override
  _AppointmentState createState() => _AppointmentState();
}

class _AppointmentState extends State<Appointment> {
  var showSpinner = false;
  var previousAppointmentId;
  var image = '';
  var employeeName = '';
  var employeeSkill = '';
  var appointmentId = '';
  var appointmentDate = '';
  var appointmentTime = '';
  var selectedServiceName;
  var selectedServiceAmount;
  var selectedServiceDescription;
  var sendData;
  String path, process, buttonText = 'Mark As A Complete';
  bool buttonShow = false;
  bool buttonShowOnly = false;

  List<ViewAppointmentService> vas = List<ViewAppointmentService>();

  @override
  void initState() {
    setState(() {
      previousAppointmentId = widget.appoinmentId;
      print('$previousAppointmentId');
      process = widget.process;
      path = widget.path;
      if (path == 'new' || path == 'current') {
        setState(() {
          buttonShow = true;
        });
      }
      if (path == 'appointmentongoing' || path == 'appointmentcompleted') {
        setState(() {
          buttonShowOnly = true;
        });
      }
    });
    GetAppointmentData();
    super.initState();
  }

  Future<void> GetAppointmentData() async {
    setState(() {
      showSpinner = true;
    });
    var res = await CallApi()
        .getWithToken('single_appointment/$previousAppointmentId');
    var body = json.decode(res.body);
    var theData = body['data'];
    var coworker = theData['user'];
    appointmentId = theData['appointment_id'];
    image = coworker['completeImage'];
    employeeName = coworker['name'];
    var expertskill = coworker['service'];
    appointmentDate = theData['date'];
    appointmentTime = theData['start_time'];
    // employeeSkill = expertskill['service_name'];
    // var showStatus = theData['appointment_status'];
    // if (showStatus == 'COMPLETE' || showStatus == 'CANCEL') {
    //   visible = 1;
    // }

    // if (showStatus == 'PENDING') {
    //   cancel = 1;
    // }
    var servicesIs = theData['service'];
    for (int i = 0; i < servicesIs.length; i++) {
      print(i);
      Map<String, dynamic> map = servicesIs[i];
      vas.add(ViewAppointmentService.fromJson(map));
    }

    setState(() {
      showSpinner = false;
    });
  }

  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;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        elevation: 0,
        backgroundColor: Colors.white,
        leading: IconButton(
          icon: Icon(
            Icons.chevron_left,
            size: 24,
            color: darkBlue,
          ),
          onPressed: () {
            Navigator.pop(context);
          },
        ),
        centerTitle: true,
        title: Text(
          'Appointment',
          style: TextStyle(
            color: darkBlue,
            fontSize: 18.0,
            fontFamily: 'FivoSansMedium',
          ),
        ),
        actions: [
          IconButton(
            icon: Icon(
              FontAwesomeIcons.bars,
              size: 22,
              color: darkBlue,
            ),
            onPressed: () {
              Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => CustomDrawer(index: 0),
                  ));
            },
          )
        ],
      ),
      body: ModalProgressHUD(
        inAsyncCall: showSpinner,
        child: GestureDetector(
          onTap: () {
            FocusScopeNode currentFocus = FocusScope.of(context);
            if (!currentFocus.hasPrimaryFocus) {
              currentFocus.unfocus();
            }
          },
          child: Stack(
            children: [
              ListView(
                scrollDirection: Axis.vertical,
                children: [
                  Padding(
                    padding: const EdgeInsets.all(15.0),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            ClipRRect(
                              borderRadius:
                                  BorderRadius.all(Radius.circular(8.0)),
                              child: Image(
                                image: NetworkImage(image),
                                height: 74.0,
                                width: 74.0,
                                fit: BoxFit.fill,
                              ),
                            ),
                            Container(
                              margin: EdgeInsets.symmetric(horizontal: 10.0),
                              alignment: Alignment.topLeft,
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.start,
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(
                                    employeeName,
                                    style: TextStyle(
                                        color: darkBlue,
                                        fontSize: 18,
                                        fontFamily: 'FivoSansMedium'),
                                  ),
                                  SizedBox(height: 5.0),
                                  Text(
                                    '$appointmentDate - $appointmentTime',
                                    style: TextStyle(
                                      color: extraDarkBlue,
                                      fontSize: 14.0,
                                      fontFamily: 'FivoSansMedium',
                                    ),
                                  ),
                                  SizedBox(height: 5.0),
                                  Text(
                                    'AP No : $appointmentId',
                                    style: TextStyle(
                                      color: extraDarkBlue,
                                      fontSize: 14,
                                      fontFamily: 'FivoSansMedium',
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                        SizedBox(height: 20.0),
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              'Selected Services',
                              style: TextStyle(
                                color: darkBlue,
                                fontSize: 18,
                                fontFamily: 'FivoSansMedium',
                              ),
                            ),
                            SizedBox(height: 10.0),
                            ListView.separated(
                              scrollDirection: Axis.vertical,
                              physics: ClampingScrollPhysics(),
                              separatorBuilder: (context, index) =>
                                  SizedBox(height: 10.0),
                              shrinkWrap: true,
                              itemCount: vas.length,
                              itemBuilder: (context, index) {
                                ViewAppointmentService viewappointmentservice =
                                    vas[index];
                                return Container(
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.all(
                                      Radius.circular(10.0),
                                    ),
                                    boxShadow: [
                                      BoxShadow(
                                        color: Colors.black26,
                                        blurRadius: 5.0,
                                        spreadRadius: 1.0,
                                      )
                                    ],
                                  ),
                                  child: Container(
                                    padding: EdgeInsets.all(5.0),
                                    decoration: BoxDecoration(
                                      color: Colors.white,
                                      borderRadius: BorderRadius.all(
                                        Radius.circular(10.0),
                                      ),
                                      boxShadow: [
                                        BoxShadow(
                                            color:
                                                Theme.of(context).primaryColor,
                                            spreadRadius: -1.0,
                                            offset: Offset(-5, 0)),
                                      ],
                                    ),
                                    child: ListTile(
                                      title: Row(
                                        children: [
                                          Expanded(
                                            child: Text(
                                              viewappointmentservice
                                                  .serviceName,
                                              style: TextStyle(
                                                color: darkBlue,
                                                fontSize: 18,
                                                fontFamily: 'FivoSansMedium',
                                              ),
                                            ),
                                          ),
                                        ],
                                      ),
                                      subtitle: Padding(
                                        padding:
                                            EdgeInsets.symmetric(vertical: 5.0),
                                        child: Column(
                                          crossAxisAlignment:
                                              CrossAxisAlignment.start,
                                          children: [
                                            Row(
                                              mainAxisAlignment:
                                                  MainAxisAlignment
                                                      .spaceBetween,
                                              children: [
                                                Text(
                                                  'Duration : ${viewappointmentservice.serviceDuration} Min',
                                                  style: TextStyle(
                                                    color: extraDarkBlue,
                                                    fontSize: 14,
                                                    fontFamily:
                                                        'FivoSansMedium',
                                                  ),
                                                ),
                                              ],
                                            ),
                                            SizedBox(height: 5.0),
                                            Text(
                                              viewappointmentservice
                                                  .serviceDiscription,
                                              style: TextStyle(
                                                color: extraDarkBlue,
                                                fontSize: 14,
                                                fontFamily: 'FivoSansMedium',
                                              ),
                                            ),
                                          ],
                                        ),
                                      ),
                                    ),
                                  ),
                                );
                              },
                            ),
                          ],
                        ),
                        SizedBox(height: 10.0),
                      ],
                    ),
                  ),
                ],
              ),
              Visibility(
                visible: buttonShow,
                child: Positioned(
                  bottom: 0.1,
                  child: Container(
                    height: 50.0,
                    width: MediaQuery.of(context).size.width,
                    child: RaisedButton(
                      onPressed: () {
                        showDialog(
                          builder: (context) => AlertDialog(
                            title: Text('Confirmation'),
                            content: Text(
                                'Are you sure to complete the appointment'),
                            actions: <Widget>[
                              FlatButton(
                                onPressed: () {
                                  var body = {
                                    'id': previousAppointmentId,
                                    'appointment_status': 'complete'
                                  };
                                  print(body);
                                  changeStatus(body);
                                },
                                child: Text('Yes'),
                              ),
                              FlatButton(
                                onPressed: () {
                                  Navigator.pop(context);
                                },
                                child: Text('No'),
                              )
                            ],
                          ),
                          context: context,
                        );
                      },
                      color: path == 'ongoing' || path == 'complete'
                          ? Color(0xFFE9F0F7)
                          : Theme.of(context).primaryColor,
                      child: Text(
                        path == 'ongoing' || path == 'complete'
                            ? process.toUpperCase()
                            : buttonText.toUpperCase(),
                        // 'Mark As A Complete',
                        style: TextStyle(
                          color: path == 'ongoing' || path == 'complete'
                              ? Color(0xFF91B4D8)
                              : Colors.white,
                          fontSize: 18.0,
                          fontFamily: 'FivoSansMedium',
                        ),
                      ),
                    ),
                  ),
                ),
              ),
              Visibility(
                visible: buttonShowOnly,
                child: Positioned(
                  bottom: 0.1,
                  child: Container(
                    height: 50.0,
                    width: MediaQuery.of(context).size.width,
                    color: Color(0xFFE9F0F7),
                    child: FlatButton(
                      onPressed: null,
                      // color: Color(0xFFE9F0F7),
                      child: Text(
                        path == 'appointmentongoing' ||
                                path == 'appointmentcompleted'
                            ? process.toUpperCase()
                            : buttonText.toUpperCase(),
                        // 'Mark As A Complete',
                        style: TextStyle(
                          color: Color(0xFF91B4D8),
                          fontSize: 18.0,
                          fontFamily: 'FivoSansMedium',
                        ),
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
