import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:doctor/patient_dashboard/BP/bp_history.dart';
import 'package:doctor/common/settings.dart';
import 'package:intl/intl.dart';

class BPCalculator extends StatefulWidget {
  String? customerId;
  BPCalculator({this.customerId});

  @override
  State<BPCalculator> createState() => _BPCalculatorState();
}

class _BPCalculatorState extends State<BPCalculator> {

  TextEditingController systoloicController = TextEditingController();
  TextEditingController diastolicController = TextEditingController();
  TextEditingController dateInput = TextEditingController();
  String bpValue = '';
  String bpText = '';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppSettings.appBar('Blood Pressure'),
        body: SingleChildScrollView(
          child: Container(
              child: Padding(
                padding: EdgeInsets.all(10),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    TextFormField(
                      cursorColor: greyColor,
                      controller: systoloicController,
                      textCapitalization: TextCapitalization.characters,
                      keyboardType: TextInputType.number,
                      decoration: const InputDecoration(
                        prefixIcon: Icon(
                          Icons.upload,
                          color: primaryColor,
                        ),
                        border: OutlineInputBorder(
                            borderSide: BorderSide(color: primaryColor)),
                        focusedBorder: OutlineInputBorder(
                          borderSide: BorderSide(color: primaryColor),
                        ),
                        enabledBorder: OutlineInputBorder(
                          borderSide: BorderSide(color: primaryColor),
                        ),
                        labelText: 'Enter systolic value',
                        labelStyle: TextStyle(
                          color: greyColor, //<-- SEE HERE
                        ),
                      ),
                    ),
                    SizedBox(height: 10),
                    TextFormField(
                      cursorColor: greyColor,
                      controller: diastolicController,
                      textCapitalization: TextCapitalization.characters,
                      keyboardType: TextInputType.number,
                      decoration: const InputDecoration(
                        prefixIcon: Icon(
                          Icons.download,
                          color: primaryColor,
                        ),
                        border: OutlineInputBorder(
                            borderSide: BorderSide(color: primaryColor)),
                        focusedBorder: OutlineInputBorder(
                          borderSide: BorderSide(color: primaryColor),
                        ),
                        enabledBorder: OutlineInputBorder(
                          borderSide: BorderSide(color: primaryColor),
                        ),
                        labelText: 'Enter diastolic value',
                        labelStyle: TextStyle(
                          color: greyColor, //<-- SEE HERE
                        ),
                      ),
                    ),
                    SizedBox(height: 10),
                    Container(
                      child: TextFormField(
                        cursorColor: greyColor,
                        controller: dateInput,
                        decoration: textFormFieldDecorationBMI(
                            Icons.calendar_today, 'Enter Date'),
                        readOnly: true,
                        onTap: () async {
                          DateTime? pickedDate = await showDatePicker(
                            context: context,
                            initialDate: DateTime.now(),
                            firstDate: DateTime(1950),
                            lastDate: DateTime.now(),
                            builder: (BuildContext context, Widget? child) {
                              return Theme(
                                data: ThemeData.dark().copyWith(
                                  colorScheme: ColorScheme.dark(
                                    primary: buttonColors,
                                    onPrimary: Colors.white,
                                    surface: buttonColors,
                                    onSurface: Colors.white,
                                  ),
                                  dialogBackgroundColor: primaryColor,
                                ),
                                child: child!,
                              );
                            },
                          );

                          if (pickedDate != null) {
                            print(
                                pickedDate); //pickedDate output format => 2021-03-10 00:00:00.000
                            String formattedDate =
                            DateFormat('dd-MM-yyyy').format(pickedDate);
                            print(
                                formattedDate); //formatted date output using intl package =>  2021-03-16
                            setState(() {
                              dateInput.text =
                                  formattedDate; //set output date to TextField value.
                            });
                          } else {}
                        },
                      ),
                    ),
                    SizedBox(height: 10),
                    Container(
                        width: double.infinity,
                        height:
                        MediaQuery.of(context).size.height * .05,
                        child: ElevatedButton(
                          style: ElevatedButton.styleFrom(
                            primary: buttonColors, // background
                            onPrimary: Colors.black, // foreground
                          ),
                          onPressed: () async {
                            if (systoloicController.text != '' &&
                                diastolicController.text != ''&&dateInput.text!='') {

                              if(int.parse(systoloicController.text)>int.parse(diastolicController.text)){
                                AppSettings.preLoaderDialog(context);
                                var payload = new Map<String, dynamic>();

                                payload["Systolic"] = double.parse(systoloicController.text.toString());
                                payload["Diastolic"] = double.parse(diastolicController.text.toString());
                                payload["date"] =dateInput.text.toString();

                                var value = await AppSettings.calculateBP(payload,widget.customerId);
                                var valueResponse = jsonDecode(value);
                                print(valueResponse);
                                setState(() {
                                  bpValue = valueResponse['userDetails']['bpCategory'].toString();
                                });
                                systoloicController.clear();
                                diastolicController.clear();
                                dateInput.clear();
                                Navigator.of(context,rootNavigator: true).pop();
                              }
                              else{
                                AppSettings.longFailedToast('Please enter diastolic value less than systolic value');
                            }
                            }
                            else{
                              AppSettings.longFailedToast('Please enter valid details');
                            }
                          },
                          child: const Text('Check BP'),
                        )),
                    SizedBox(height: 20),
                    Container(
                        child: Row(
                          children: [
                            Text(bpValue,style: TextStyle(color: Colors.red,fontWeight: FontWeight.bold,fontSize: 15),),
                          ],
                        )
                    ),
                    SizedBox(height: 20),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Column(
                          children: [
                            IconButton(
                              onPressed: () {
                                Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                      builder: (context) =>  BPHistory(customerId: widget.customerId,)),
                                );
                              },
                              icon: Icon(
                                Icons.history,
                                color: primaryColor,
                                size: 40,
                              ),
                            ),
                            SizedBox(height: 10),
                            Padding(padding: EdgeInsets.fromLTRB(10,0,0,0),
                              child: Container(
                                child: Text('History',style:TextStyle(color:Colors.black,fontSize: 12,fontWeight: FontWeight.bold,)),
                              ),)
                          ],
                        ),
                        ElevatedButton(
                          style: ElevatedButton.styleFrom(
                            primary: buttonColors, // background
                            onPrimary: Colors.black, // foreground
                          ),
                          onPressed: () async {
                            Navigator.pop(context);
                          },
                          child: const Text('Cancel'),
                        )
                      ],
                    )


                  ],
                ),
              )
          ),
        )
    );
  }
}
