import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:healthcare_pharmacy/adddeliveryboy.dart';
import 'package:healthcare_pharmacy/dashboard.dart';
import 'package:healthcare_pharmacy/models/getdeliveryboy_model.dart';
import 'package:healthcare_pharmacy/settings.dart';

class GetDeliveryboyData extends StatefulWidget {



  @override
  State<GetDeliveryboyData> createState() => _GetDeliveryboyDataState();
}
class _GetDeliveryboyDataState extends State<GetDeliveryboyData> {
  List<GetDeliveryboyDetailsModel> modeldeliveryboyList = [];
  TextEditingController deliveryboyNameController = TextEditingController();
  TextEditingController deliveryboyPhoneController = TextEditingController();
  TextEditingController deliveryboyAlterPhoneController = TextEditingController();
  TextEditingController deliveryboyAddress = TextEditingController();
  TextEditingController deliveryboyStatus = TextEditingController();


  bool isLoading=false;

  Future<void> readJson() async {
    var response1= await AppSettings.getAllDeliverboy();
    print(response1);
    setState(() {
      modeldeliveryboyList =
          ((jsonDecode(response1)['deliveryBoys']) as List).map((dynamic model) {
            return GetDeliveryboyDetailsModel.fromJson(model);
          }).toList();
      isLoading=false;
    });
  }

  @override
  void initState() {
    isLoading=true;
    readJson();
    super.initState();
  }

  showUpdateDeliveryDialog(var object) async {
    deliveryboyNameController.text=object.deliveryboy_name??'';
    deliveryboyPhoneController.text=object.deliveryboy_phone??'';
    deliveryboyAlterPhoneController.text=object.deliveryboy_alternativeContactNumber??'';
    deliveryboyAddress.text=object.deliveryboy_address??'';
    return showDialog(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return StatefulBuilder(
            builder: (BuildContext context, StateSetter setState) {
              return AlertDialog(
                title: const Text('Update Deliveryboy'),
                content: SingleChildScrollView(
                  child: ListBody(
                    children: <Widget>[
                      Container(
                        padding: const EdgeInsets.fromLTRB(10, 10, 10, 0),
                        child: TextFormField(
                          cursorColor: greyColor,
                          controller: deliveryboyNameController,
                          textCapitalization: TextCapitalization.characters,
                          decoration: const InputDecoration(
                            prefixIcon: Icon(
                              Icons.ac_unit_outlined,
                              color: greyColor,
                            ),
                            border: OutlineInputBorder(
                                borderSide: BorderSide(color: greyColor)),
                            focusedBorder: OutlineInputBorder(
                              borderSide: BorderSide(color: greyColor),
                            ),
                            enabledBorder: OutlineInputBorder(
                              borderSide: BorderSide(color: greyColor),
                            ),
                            labelText: 'Enter  name',
                            labelStyle: TextStyle(
                              color: greyColor, //<-- SEE HERE
                            ),
                          ),
                        ),
                      ),
                      Container(
                        padding: const EdgeInsets.fromLTRB(10, 10, 10, 0),
                        child: TextFormField(
                          cursorColor: greyColor,
                          controller: deliveryboyPhoneController,
                          keyboardType: TextInputType.number,
                          decoration: const InputDecoration(
                            prefixIcon: Icon(
                              Icons.phone,
                              color: greyColor,
                            ),
                            border: OutlineInputBorder(
                                borderSide: BorderSide(color: greyColor)),
                            focusedBorder: OutlineInputBorder(
                              borderSide: BorderSide(color: greyColor),
                            ),
                            enabledBorder: OutlineInputBorder(
                              borderSide: BorderSide(color: greyColor),
                            ),
                            labelText: 'Enter phone number',
                            labelStyle: TextStyle(
                              color: greyColor, //<-- SEE HERE
                            ),
                          ),
                        ),
                      ),
                      Container(
                        padding: const EdgeInsets.fromLTRB(10, 10, 10, 0),
                        child: TextFormField(
                          cursorColor: greyColor,
                          controller: deliveryboyAlterPhoneController,
                          keyboardType: TextInputType.number,
                          decoration: const InputDecoration(
                            prefixIcon: Icon(
                              Icons.phone,
                              color: greyColor,
                            ),
                            border: OutlineInputBorder(
                                borderSide: BorderSide(color: greyColor)),
                            focusedBorder: OutlineInputBorder(
                              borderSide: BorderSide(color: greyColor),
                            ),
                            enabledBorder: OutlineInputBorder(
                              borderSide: BorderSide(color: greyColor),
                            ),
                            labelText: 'Enter Alternative phone number',
                            labelStyle: TextStyle(
                              color: greyColor, //<-- SEE HERE
                            ),
                          ),
                        ),
                      ),

                    ],
                  ),
                ),
                actions: <Widget>[
                  TextButton(
                    child:  Text('Cancel',style:textButtonStyle()),
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                  ),
                  TextButton(
                    child:  Text('Update',style:textButtonStyle()),
                    onPressed: () async{
                      if (deliveryboyNameController.text != '' ) {
                        AppSettings.preLoaderDialog(context);

                        Map<String, dynamic> payload = {
                          "pharmacyname": "string",
                          "name": deliveryboyNameController.text.toString(),
                          "alternativeContactNumber": deliveryboyAlterPhoneController.text.toString(),
                          "phone": deliveryboyPhoneController.text.toString(),
                          "address": deliveryboyAddress.text.toString(),
                          "city": "string",
                          "state": "string",
                          "zip": "string",
                          "status": "active",
                          "longitude": 0,
                          "latitude": 0,
                          "fcmId": "string"
                        };

                        bool offerStatus = await AppSettings.updateDeliveryboy(object.deliveryboy_phone, payload);
                        try {
                          if (offerStatus) {
                            Navigator.of(context, rootNavigator: true).pop();
                            AppSettings.longSuccessToast(
                                "Deliveryboy Updated Successfully");
                            deliveryboyNameController.text = '';
                            deliveryboyAlterPhoneController.text = '';
                            deliveryboyPhoneController.text = '';
                            Navigator.of(context).pop();
                            await readJson();

                          } else {
                            Navigator.of(context, rootNavigator: true).pop();
                            AppSettings.longFailedStyledToast(
                                "Deliveryboy upadtion failed", context);
                            Navigator.of(context).pop();
                          }
                        } catch (exception) {
                          Navigator.of(context).pop();
                          print(exception);
                        }
                      } else {
                        AppSettings.longFailedStyledToast("enter details", context);
                      }
                    },
                  ),
                ],
              );
            });
      },
    );
  }


  Widget renderzUi(){
    if(modeldeliveryboyList.length!=0){

      return  Column(
          crossAxisAlignment: CrossAxisAlignment.end,
          children: [
            Expanded(child:ListView.builder(
                padding:  EdgeInsets.all(0),
                itemCount: modeldeliveryboyList .length,
                itemBuilder: (context,index){
                  var data=modeldeliveryboyList[index];
                  return GestureDetector(
                    onTap: () {

                    },
                    child: Card(
                      child: ListTile(
                        title: RichText(
                          text: TextSpan(
                            style: DefaultTextStyle.of(context).style,
                            children: <TextSpan>[
                              TextSpan(
                                text: 'Name: ',
                                style: TextStyle(
                                  color: Colors.black,
                                  fontSize: 16,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                              TextSpan(
                                text: modeldeliveryboyList[index].deliveryboy_name,
                                style: TextStyle(
                                  fontSize: 16,
                                  color: primaryColor,
                                ),
                              ),
                            ],
                          ),
                        ),

                        subtitle: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            SizedBox(height:5),
                            RichText(
                              text: TextSpan(
                                style: DefaultTextStyle.of(context).style,
                                children: <TextSpan>[
                                  TextSpan(
                                    text: 'phone: ',
                                    style: TextStyle(
                                      fontSize: 16,
                                      color: Colors.black, // Change the color for "Description" text
                                      fontWeight: FontWeight.bold, // You can apply other styles too
                                    ),
                                  ),
                                  TextSpan(
                                    text: modeldeliveryboyList[index].deliveryboy_phone,
                                    style: TextStyle(
                                      fontSize: 16,
                                      color: primaryColor, // Change the color for description content
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            SizedBox(height:5),
                            RichText(
                              text: TextSpan(
                                style: DefaultTextStyle.of(context).style,
                                children: <TextSpan>[
                                  TextSpan(
                                    text: 'alternative phone: ',
                                    style: TextStyle(
                                      fontSize: 16,
                                      color: Colors.black, // Change the color for "Description" text
                                      fontWeight: FontWeight.bold, // You can apply other styles too
                                    ),
                                  ),
                                  TextSpan(
                                    text: modeldeliveryboyList[index].deliveryboy_alternativeContactNumber,
                                    style: TextStyle(
                                      fontSize: 16,
                                      color:primaryColor, // Change the color for description content
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            SizedBox(height:5),
                            RichText(
                              text: TextSpan(
                                style: DefaultTextStyle.of(context).style,
                                children: <TextSpan>[
                                  TextSpan(
                                    text: 'address: ',
                                    style: TextStyle(
                                      fontSize: 16,
                                      color: Colors.black, // Change the color for "Description" text
                                      fontWeight: FontWeight.bold, // You can apply other styles too
                                    ),
                                  ),
                                  TextSpan(
                                    text: modeldeliveryboyList[index].deliveryboy_address,

                                    style: TextStyle(
                                      fontSize: 16,
                                      color:primaryColor, // Change the color for description content
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            SizedBox(height:10),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                IconButton(
                                  icon: Icon(Icons.edit),
                                  onPressed: () {
                                    showUpdateDeliveryDialog(modeldeliveryboyList[index]);
                                  },
                                ),
                                IconButton(
                                  icon: const Icon(Icons.delete,color: primaryColor,),

                                  onPressed: () async{
                                    showDialog(
                                      //if set to true allow to close popup by tapping out of the popup
                                      //barrierDismissible: false,
                                      context: context,
                                      builder: (BuildContext context) => AlertDialog(
                                        title: const Text('Do you want to delete Delivery Boy?',
                                            style: TextStyle(
                                              color: primaryColor,
                                              fontSize: 20,
                                            )),
                                        actionsAlignment: MainAxisAlignment.spaceBetween,
                                        actions: [
                                          TextButton(
                                            onPressed: ()async {
                                              bool deleteDeliveryboyStatus = await AppSettings.deleteDeliveryboy(modeldeliveryboyList[index].deliveryboy_phone);


                                              if(deleteDeliveryboyStatus){
                                                readJson();
                                                AppSettings.longSuccessToast('Deliveryboy deleted successfully');
                                                Navigator.of(context).pop(true);

                                              }
                                              else{
                                                AppSettings.longFailedToast('Deliveryboy deletion failed');
                                              }
                                            },
                                            child: const Text('Yes',
                                                style: TextStyle(
                                                  color: primaryColor,
                                                  fontSize: 20,
                                                )),
                                          ),
                                          TextButton(
                                            onPressed: () {
                                              Navigator.of(context).pop(true);
                                            },
                                            child: const Text('No',
                                                style: TextStyle(
                                                  color: primaryColor,
                                                  fontSize: 20,
                                                )),
                                          ),
                                        ],
                                      ),
                                    );



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






                }) ),
            Padding(
              padding: EdgeInsets.fromLTRB(8, 8, 8, 8),
              child: CircleAvatar(
                backgroundColor: primaryColor,
                radius: 40,
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: <Widget>[
                    IconButton(
                      iconSize: 40,
                      icon: const Icon(
                        Icons.add,
                        color: Colors.white,
                      ),
                      onPressed: () async{
                        Navigator.pop(context);
                        await Navigator.push(
                          context,
                          MaterialPageRoute(
                              builder: (context) => Deliverboy()),
                        );
                        //showBoreAddingDialog();
                      },
                    ),
                    /* Padding(
                      padding: EdgeInsets.fromLTRB(5, 0, 5, 5),
                      child: Text(
                        'Add Tanks ',
                        style: TextStyle(color: Colors.white),
                      ),
                    )*/
                  ],
                ),
              ),
            ),
          ]);
    }
    else{
      return  Center(
          child: Padding(
            padding: EdgeInsets.fromLTRB(0, 40, 0, 0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                SizedBox(height: MediaQuery.of(context).size.height * .25,),
                Text('Click below icon to add new Delivery Boy'),
                SizedBox(
                  height: 20,
                ),
                CircleAvatar(
                  backgroundColor: primaryColor,
                  radius: 40,
                  child: IconButton(
                    iconSize: 40,
                    icon: const Icon(
                      Icons.add,
                      color: Colors.white,
                    ),
                    onPressed: () async {
                      Navigator.pop(context);
                      await Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (context) => Deliverboy()),
                      );
                    },
                  ),
                )
              ],
            ),
          )
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
        child: Scaffold(
          appBar: AppBar(
            title: Text('Delivery Boy'),
            backgroundColor: primaryColor,
            leading: IconButton(
              icon: Icon(Icons.arrow_back),
              onPressed: () async {
                await Navigator.push(
                  context,
                  MaterialPageRoute(
                      builder: (context) => const Dashboard()),
                );
              },
            ),
           ),

          body: isLoading?Center(
            child: CircularProgressIndicator(
              color: primaryColor,
              strokeWidth: 5.0,
            ),
          ):renderzUi(),
        ));
  }
}
