import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:watermanagement/addtankers.dart';

import 'package:watermanagement/settings.dart';

import 'models/tankersview_model.dart';

class TankersView extends StatefulWidget {



  @override
  State<TankersView> createState() => _TankersViewState();
}

class _TankersViewState extends State<TankersView> {

  List<GetTanksDetailsModel> modelTanksViewList = [];
  TextEditingController tankerNameController = TextEditingController();
  TextEditingController tankerPhoneController = TextEditingController();
  TextEditingController tankerAlterPhoneController = TextEditingController();
  TextEditingController updateTankerNameController = TextEditingController();
  TextEditingController updateTankerDescriptionController = TextEditingController();
  TextEditingController updateTankerPhoneNumberController = TextEditingController();
  TextEditingController updateTankerAlternatePhoneNumberController = TextEditingController();
  TextEditingController updateTankerCapacityController = TextEditingController();
  TextEditingController updateTankerpriceController = TextEditingController();
  TextEditingController tankerBorePriceController = TextEditingController();
  TextEditingController tankerDrinkingPriceController = TextEditingController();

  bool isLoading=false;
  /*bool isDrinkingChecked = false;
  bool isBoreChecked = false;
  List waterTypes = [];
  List waterPrice = [];*/
  String dropdownTypeOfWater = 'bore water';
  var typeOfWaterItems = [
    'bore water',
    'drinking water',
  ];

  List updateWaterTypes = [];


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

  @override
  void initState() {
    isLoading=true;
    readJson();
    super.initState();
  }
  showUpdateTankerDialog(var object) async {
    updateTankerNameController.text = object.tanker_name;
    updateTankerDescriptionController.text = '';
    updateTankerPhoneNumberController.text = object.tanker_phone;
    updateTankerCapacityController.text=object.capacity;
    updateTankerpriceController.text=object.waterprice;
    updateTankerAlternatePhoneNumberController.text = object.tanker_alterphone;
    setState(() {
      dropdownTypeOfWater=object.type_of_water.toString().toLowerCase()??'';
    });


   /* isDrinkingChecked=object.isDrinking;
    isBoreChecked = object.isBore;
    if(object.pricetype.length==2){
      tankerDrinkingPriceController.text=object.pricetype[0].toString();
      tankerBorePriceController.text=object.pricetype[1].toString();
    }
    else{
      tankerDrinkingPriceController.text=object.pricetype[0].toString();
      tankerBorePriceController.text='';
    }*/


    return showDialog(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return StatefulBuilder(
            builder: (BuildContext context, StateSetter setState) {
              return AlertDialog(
                title: const Text('Update Tanker'),
                content: SingleChildScrollView(
                  child: ListBody(
                    children: <Widget>[
                      Container(
                        //padding: const EdgeInsets.fromLTRB(10, 10, 10, 0),
                        child: TextFormField(
                          cursorColor: greyColor,
                          controller: updateTankerNameController,
                          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 update tanker supplier name',
                            labelStyle: TextStyle(
                              color: greyColor, //<-- SEE HERE
                            ),
                          ),
                        ), //tanker name
                      ),
                      const SizedBox(
                        height: 30,
                      ),
                  /*    Container(
                        //padding: const EdgeInsets.fromLTRB(10, 10, 10, 0),
                        child: TextFormField(
                          cursorColor: greyColor,
                          controller: updateTankerPhoneNumberController,
                          keyboardType: TextInputType.number,
                          decoration: const InputDecoration(
                            prefixIcon: Icon(
                              Icons.phone_android,
                              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
                            ),
                          ),
                        ),
                      ), //phone number
                      const SizedBox(
                        height: 30,
                      ),
                      Visibility(
                          visible: true,
                          child: Container(
                            //padding: const EdgeInsets.fromLTRB(10, 10, 10, 0),
                            child: TextFormField(
                              cursorColor: greyColor,
                              controller:
                              updateTankerAlternatePhoneNumberController,
                              keyboardType: TextInputType.number,
                              decoration: const InputDecoration(
                                prefixIcon: Icon(
                                  Icons.phone_android,
                                  color: greyColor,
                                ),
                                border: OutlineInputBorder(
                                    borderSide: BorderSide(color: greyColor)),
                                focusedBorder: OutlineInputBorder(
                                  borderSide: BorderSide(color: greyColor),
                                ),
                                enabledBorder: OutlineInputBorder(
                                  borderSide: BorderSide(color: greyColor),
                                ),
                                labelText: 'Enter alternate phone number',
                                labelStyle: TextStyle(
                                  color: greyColor, //<-- SEE HERE
                                ),
                              ),
                            ),
                          )), //alternate phone number
                      const SizedBox(
                        height: 30,
                      ),*/
                      Visibility(
                          visible: true,
                          child: Container(
                            //padding: const EdgeInsets.fromLTRB(10, 10, 10, 0),
                            child: TextFormField(
                              onChanged: (value) {
                                value = '${AppSettings.formNum(
                                  value.replaceAll(',', ''),
                                )}';
                                updateTankerCapacityController.value = TextEditingValue(
                                  text: value,
                                  selection: TextSelection.collapsed(
                                    offset: value.length,
                                  ),
                                );
                              },
                              cursorColor: greyColor,
                              controller: updateTankerCapacityController,
                              keyboardType: TextInputType.number,
                              decoration: InputDecoration(
                                prefixIcon: Icon(
                                  Icons.ac_unit_outlined,
                                  color: greyColor,
                                ),
                                suffix: capacitySuffixText(),
                                border: OutlineInputBorder(
                                    borderSide: BorderSide(color: greyColor)),
                                focusedBorder: OutlineInputBorder(
                                  borderSide: BorderSide(color: greyColor),
                                ),
                                enabledBorder: OutlineInputBorder(
                                  borderSide: BorderSide(color: greyColor),
                                ),
                                labelText: 'Enter Capacity',
                                labelStyle: TextStyle(
                                  color: greyColor, //<-- SEE HERE
                                ),
                              ),
                            ),
                          )), //capacity
                      const SizedBox(
                        height: 30,
                      ),


                      Container(
                        child: DropdownButtonFormField(
                          // Initial Value
                          value: dropdownTypeOfWater,
                          isExpanded: true,
                          decoration: const InputDecoration(
                            prefixIcon: Icon(
                              Icons.water,
                              color: greyColor,
                            ),
                            border: OutlineInputBorder(
                                borderSide: BorderSide(color: greyColor)),
                            focusedBorder: OutlineInputBorder(
                              borderSide: BorderSide(color: greyColor),
                            ),
                            enabledBorder: OutlineInputBorder(
                              borderSide: BorderSide(color: greyColor),
                            ),
                            labelText: 'Type of water storage',
                            labelStyle: TextStyle(
                              color: greyColor, //<-- SEE HERE
                            ),
                          ),

                          hint: Text('Select Type of water'),
                          // Down Arrow Icon
                          icon: const Icon(Icons.keyboard_arrow_down),

                          // Array list of items
                          items: typeOfWaterItems.map((String items) {
                            return DropdownMenuItem(
                              value: items,
                              child: Text(items),
                            );
                          }).toList(),
                          // After selecting the desired option,it will
                          // change button value to selected value
                          onChanged: (String? newValue) {
                            setState(() {
                              dropdownTypeOfWater = newValue!;
                            });
                          },
                        ),
                      ),
                      const SizedBox(
                        height: 30,
                      ),
                      Container(
                        //padding: const EdgeInsets.fromLTRB(10, 10, 10, 0),
                        child: TextFormField(
                          cursorColor: greyColor,
                          controller: updateTankerpriceController,
                          textCapitalization: TextCapitalization.characters,
                          decoration: const InputDecoration(
                            prefixIcon: Icon(
                              Icons.currency_rupee,
                              color: greyColor,
                            ),
                            border: OutlineInputBorder(
                                borderSide: BorderSide(color: greyColor)),
                            focusedBorder: OutlineInputBorder(
                              borderSide: BorderSide(color: greyColor),
                            ),
                            enabledBorder: OutlineInputBorder(
                              borderSide: BorderSide(color: greyColor),
                            ),
                            labelText: 'Enter update price',
                            labelStyle: TextStyle(
                              color: greyColor, //<-- SEE HERE
                            ),
                          ),
                        ), //tanker name
                      ),















                      /*Container(
                          padding: EdgeInsets.fromLTRB(20, 0, 20, 0),
                          child: Visibility(
                              visible: true,
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(
                                    'Choose type of water',
                                    style: TextStyle(color: primaryColor,fontSize: 20),
                                  ),

                                  SizedBox(height:10),
                                  Row(
                                    children: [
                                      Text(
                                        'Drinking',
                                        style: TextStyle(color: Colors.black,fontSize: 20),
                                      ),
                                      Checkbox(
                                        checkColor: Colors.white,
                                        activeColor: primaryColor,
                                        value: isDrinkingChecked,
                                        onChanged: (bool? value) {
                                          setState(() {
                                            isDrinkingChecked = value!;
                                          });
                                          if (isDrinkingChecked) {

                                            object.updatedWaterTypes
                                                .add({'typeofwater': 'Drinking Water'});
                                            // waterPrice.add({'price': tankerDrinkingPriceController.text.toString()});

                                          } else {

                                            object.updatedWaterTypes.removeWhere((e) => e['typeofwater'].toString().toUpperCase() == 'DRINKING WATER');
                                            // waterPrice.removeWhere((e) => e['price'].toString().toUpperCase() == tankerDrinkingPriceController.text.toString());
                                          }
                                        },
                                      ),



                                      Visibility(
                                        visible: isDrinkingChecked,
                                        child: Container(
                                          height: 37,
                                          width:120,
                                          child:TextFormField(
                                            cursorColor: greyColor,
                                            controller: tankerDrinkingPriceController,
                                            keyboardType: TextInputType.number,
                                            decoration: const InputDecoration(
                                              prefixIcon: Icon(
                                                Icons.currency_rupee,
                                                color: greyColor,
                                              ),
                                              border: OutlineInputBorder(
                                                  borderSide: BorderSide(color: greyColor)),
                                              focusedBorder: OutlineInputBorder(
                                                borderSide: BorderSide(color: greyColor),
                                              ),
                                              enabledBorder: OutlineInputBorder(
                                                borderSide: BorderSide(color: greyColor),
                                              ),
                                              labelText: 'Enter Price',
                                              labelStyle: TextStyle(
                                                color: greyColor, //<-- SEE HERE
                                              ),
                                              contentPadding: EdgeInsets.all(5),
                                            ),
                                          ),

                                        ),
                                      )

                                    ],
                                  ),

                                  SizedBox(height:10),

                                  Row(
                                    children: [
                                      Text(
                                        'Bore',
                                        style: TextStyle(color: Colors.black,fontSize: 20),
                                      ),
                                      SizedBox(width: 35),
                                      Checkbox(
                                        checkColor: Colors.white,
                                        activeColor: primaryColor,
                                        value: isBoreChecked,
                                        onChanged: (bool? value) {
                                          setState(() {
                                            isBoreChecked = value!;
                                          });
                                          if (isBoreChecked) {

                                            object.updatedWaterTypes
                                                .add({'typeofwater': 'Bore Water'});
                                          } else {

                                            object.updatedWaterTypes.removeWhere((e) => e['typeofwater'].toString().toUpperCase() == 'BORE WATER');
                                          }
                                        },
                                      ),

                                      Visibility(
                                        visible: isBoreChecked,
                                        child: Container(
                                          height: 37,
                                          width:120,
                                          child:TextFormField(
                                            cursorColor: greyColor,
                                            controller: tankerBorePriceController,
                                            keyboardType: TextInputType.number,
                                            decoration: const InputDecoration(
                                              prefixIcon: Icon(
                                                Icons.currency_rupee,
                                                color: greyColor,
                                              ),
                                              border: OutlineInputBorder(
                                                  borderSide: BorderSide(color: greyColor)),
                                              focusedBorder: OutlineInputBorder(
                                                borderSide: BorderSide(color: greyColor),
                                              ),
                                              enabledBorder: OutlineInputBorder(
                                                borderSide: BorderSide(color: greyColor),
                                              ),
                                              labelText: 'Enter Price',
                                              labelStyle: TextStyle(
                                                color: greyColor, //<-- SEE HERE
                                              ),
                                              contentPadding: EdgeInsets.all(5),
                                            ),
                                          ),

                                        ),)

                                    ],
                                  )
                                ],
                              ))
                      ),*/
                    ],
                  ),
                ),
                actions: <Widget>[
                  TextButton(
                    child: Text('cancel', style: textButtonStyle()),
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                  ),
                  TextButton(
                    child: Text('Update', style: textButtonStyle()),
                    onPressed: () async {
                      if (updateTankerNameController.text != '' ) {
/*
                        waterPrice=[];
                        if(isDrinkingChecked){
                          waterPrice.add({'price': tankerDrinkingPriceController.text.toString()});
                        }

                        if(isBoreChecked){
                          waterPrice.add({'price': tankerBorePriceController.text.toString()});
                        }*/

                        AppSettings.preLoaderDialog(context);

                        var payload = new Map<String, dynamic>();

                        payload["tankerName"] = updateTankerNameController.text.toString();
                        payload["phoneNumber"] = updateTankerPhoneNumberController.text.toString();
                        payload["alternative_phoneNumber"] = updateTankerAlternatePhoneNumberController.text.toString();
                        payload["capacity"] = updateTankerCapacityController.text.toString();
                      //  payload["typeofwater"] = object.updatedWaterTypes;
                        payload["typeofwater"] = dropdownTypeOfWater.toString();
                        payload["price"] = updateTankerpriceController.text.toString();
                        payload["supplier_address"] = AppSettings.supplierAddress;
                        payload["supplier_name"] = AppSettings.suppliername;


                        bool tankStatus = await AppSettings.updateTanker(object.tanker_name, payload);
                        try {
                          if (tankStatus) {
                            Navigator.of(context, rootNavigator: true).pop();
                            AppSettings.longSuccessToast(
                                "Tanker Updated Successfully");
                            updateTankerNameController.text = '';
                            updateTankerPhoneNumberController.text = '';
                            updateTankerAlternatePhoneNumberController.text='';
                            updateTankerCapacityController.text='';
                            updateTankerpriceController.text='';
                            Navigator.of(context).pop();
                            await readJson();
                          } else {
                            Navigator.of(context, rootNavigator: true).pop();
                            AppSettings.longFailedStyledToast(
                                "Tanker upadtion failed", context);
                            Navigator.of(context).pop();
                          }
                        } catch (exception) {
                          Navigator.of(context).pop();
                          print(exception);
                        }
                      } else {
                        AppSettings.longFailedStyledToast("enter details", context);
                      }
                    },
                  ),
                ],
              );
            });
      },
    );
  }


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

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

                    color: modelTanksViewList[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: Column(
                              children: [
                                Row(
                                  mainAxisAlignment: MainAxisAlignment.start,
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Column(
                                      mainAxisAlignment: MainAxisAlignment.start,
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        Text('tankerName :',style: labelTextStyle()),
                                        Text('Capacity :',style: labelTextStyle()),
                                        Text('Type Of Water :',style: labelTextStyle()),
                                        Text('price :',style: labelTextStyle()),
                                      ],
                                    ),
                                    SizedBox(width: 5,),
                                    Column(
                                      mainAxisAlignment: MainAxisAlignment.start,
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        Text(modelTanksViewList[index].tanker_name,style: valuesTextStyle()),
                                        //Text(modelTanksViewList[index].tanker_phone,style: valuesTextStyle()),
                                       // Text(modelTanksViewList[index].tanker_alterphone,style: valuesTextStyle()),
                                        Text(modelTanksViewList[index].capacity+'   Ltrs',style: valuesTextStyle()),
                                        Text(modelTanksViewList[index].type_of_water,style: valuesTextStyle()),
                                        Text(modelTanksViewList[index].waterprice,style: valuesTextStyle()),
                                      ],
                                    ),
                                  ],
                                ),
                              ],
                            ),
                          ),

                          Expanded(child:IconButton(
                            icon: const Icon(Icons.edit,color: primaryColor,),
                            onPressed: () {
                              showUpdateTankerDialog(modelTanksViewList[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 deleteTankStatus = await AppSettings.deleteTanker(modelTanksViewList[index].tanker_name);


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

                                        }
                                        else{
                                          AppSettings.longFailedToast('tank 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) => AddTankers()),
                        );
                        //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 Tanker'),
                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) => AddTankers()),
                      );
                    },
                  ),
                )
              ],
            ),
          )
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
        child: Scaffold(
          appBar: AppSettings.appBar('Tankers'),
          body: isLoading?Center(
            child: CircularProgressIndicator(
              color: primaryColor,
              strokeWidth: 5.0,
            ),
          ):renderzUi(),
        ));
  }
}
