import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:watermanagement/adddeliveryboy.dart';
import 'package:watermanagement/models/getdeliveryboy_model.dart';
import 'package:watermanagement/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)['data']) as List).map((dynamic model) {
            return GetDeliveryboyDetailsModel.fromJson(model);
          }).toList();
      isLoading=false;
    });
  }

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

  showUpdateDeliveryDialog(var object) async {
    // tankNameController
    // blockNameController
    // capacityController
    deliveryboyNameController.text=object.deliveryboy_name??'';
    deliveryboyPhoneController.text=object.deliveryboy_phone??'';
    deliveryboyAlterPhoneController.text=object.deliveryboy_alternativeContactNumber??'';
    deliveryboyAddress.text=object.deliveryboy_address??'';
    deliveryboyStatus.text=object.deliveryboy_status??'';



    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!=''&&deliveryboyPhoneController.text!=''&&deliveryboyAlterPhoneController.text!=''){
                        var payload = new Map<String, dynamic>();
                        payload["name"] = deliveryboyNameController.text.toString();
                        payload["phone"] = deliveryboyPhoneController.text.toString();
                        payload["alternativeContactNumber"] = deliveryboyAlterPhoneController.text.toString();
                        bool updateDeliveryboyStatus = await AppSettings.updateDeliveryboy(object.deliveryboy_phone,payload);
                        if(updateDeliveryboyStatus){
                          readJson();
                          AppSettings.longSuccessToast('Deliveryboy updated successfully');
                          Navigator.of(context).pop(true);
                        }
                        else{
                          AppSettings.longFailedToast('Deliveryboy update failed');
                        }
                      }
                      else{
                        AppSettings.longFailedToast('Fill the details');
                      }
                    },
                  ),
                ],
              );
            });
      },
    );
  }

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

      return  Column(
          crossAxisAlignment: CrossAxisAlignment.end,
          children: [
            Expanded(child:ListView.builder(
                padding:  EdgeInsets.all(0),
                itemCount: modeldeliveryboyList.length,
                itemBuilder: (BuildContext context, int index) {
                  return Card(

                    color: modeldeliveryboyList[index].cardColor,
                    child: Padding(
                      padding:EdgeInsets.all(8) ,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [

                          Container(
                            //width: MediaQuery.of(context).size.width * .55,
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.start,
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Column(
                                  mainAxisAlignment: MainAxisAlignment.start,
                                  crossAxisAlignment: CrossAxisAlignment.start,

                                  children: [
                                    Text('name :',style: labelTextStyle()),
                                    Text('phone :',style: labelTextStyle()),
                                    Text('alternativeContactNumber :',style: labelTextStyle()),
                                   // Text('address :',style: labelTextStyle()),
                                  ],
                                ),
                                SizedBox(width: 5,),
                                Column(
                                  mainAxisAlignment: MainAxisAlignment.start,
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text(modeldeliveryboyList[index].deliveryboy_name,style: valuesTextStyle()),
                                    Text(modeldeliveryboyList[index].deliveryboy_phone,style: valuesTextStyle()),
                                    Text(modeldeliveryboyList[index].deliveryboy_alternativeContactNumber,style: valuesTextStyle()),
                                    /*Text(modeldeliveryboyList[index].deliveryboy_address,style: valuesTextStyle(),
                                      overflow: TextOverflow.ellipsis,
                                      maxLines: 1),*/
                                  ],
                                ),
                              ],
                            ),
                          ),
                          Expanded(child:IconButton(
                            icon: const Icon(Icons.edit,color: primaryColor,),
                            onPressed: () {
                              showUpdateDeliveryDialog(modeldeliveryboyList[index]);
                            },
                          ),),
                          Expanded(child: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 tank?',
                                      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 Deliveryboy'),
                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: AppSettings.appBar('Deliveryboy'),
          body: isLoading?Center(
            child: CircularProgressIndicator(
              color: primaryColor,
              strokeWidth: 5.0,
            ),
          ):renderzUi(),
        ));
  }
}
