
import 'package:flutter/material.dart';
import 'package:watermanagement/settings.dart';
import 'package:watermanagement/tankersview.dart';

import 'dashboard.dart';

class AddTankers extends StatefulWidget {
  const AddTankers({Key? key}) : super(key: key);

  @override
  State<AddTankers> createState() => _AddTankersState();
}

class _AddTankersState extends State<AddTankers> {


  TextEditingController tankerNameController = TextEditingController();
  TextEditingController tankerPhoneNumberController = TextEditingController();
  TextEditingController tankerAlternativePhoneNumberController = TextEditingController();
  TextEditingController tankerDrinkingPriceController = TextEditingController();
  TextEditingController tankerBorePriceController = TextEditingController();
  TextEditingController tankerCapacityController = TextEditingController();
  TextEditingController tankerPriceController = TextEditingController();

  bool isCapacityText = false;
  bool isLoading = false;
  bool isTankerDataLoading = false;
  bool isBoreDataLoading = false;
  bool isGovtPipelineDataLoading = false;

  bool isDrinkingChecked = false;
  bool isBoreChecked = false;
  bool isFiveChecked = false;
  bool isTenChecked = false;
  bool isFifteenChecked = false;
  bool isTwentyChecked = false;
  bool isUpdateDrinkingChecked = false;
  bool isUpdateBoreChecked = false;
  bool isUpdateFiveChecked = false;

  bool isUpdateTenChecked = false;
  bool isUpdateFifteenChecked = false;
  bool isUpdateTwentyChecked = false;

/*
  bool isPriceDrinking = false;
  bool isPriceBore = false;*/

  List waterTypes = [];
  List waterPrice = [];

  List updateWaterTypes = [];

  late TabController _controller;

  String dropdownTypeOfWaterForUpadetBore = 'Bore water';
  String dropdownTypeOfWaterForTanker = 'Drinking';
  String dropdownTypeOfWater = 'Bore water';
  var typeOfWaterItems = [
    'Bore water',
    'Drinking Water',
  ];
  var typeOfWaterForUpadetBore = [
    'Bore water',
    'Drinking Water',
  ];
  var typeOfWaterItemsForTanker = [
    'Drinking',
    'Bore',
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppSettings.appBar('Add Tanker'),
      body: SafeArea(
          child: SingleChildScrollView(
            child: Column(
              children: <Widget>[
                const SizedBox(
                  height: 55,
                ),
                Container(
                    height: MediaQuery.of(context).size.height * .15,
                    width: double.infinity,
                    child: Image(
                      image: const AssetImage('images/logo.png'),
                      height: MediaQuery.of(context).size.height * .25,
                    )),
                const SizedBox(
                  height: 15,
                ),
                Container(
                  //padding: const EdgeInsets.fromLTRB(10, 10, 10, 0),
                  padding: const EdgeInsets.all(10),
                  child: TextFormField(
                    cursorColor: greyColor,
                    controller: tankerNameController,
                    textCapitalization: TextCapitalization.characters,
                    decoration: const InputDecoration(
                      prefixIcon: Icon(
                        Icons.propane_tank,
                        color: greyColor,
                      ),
                      border: OutlineInputBorder(
                          borderSide: BorderSide(color: greyColor)),
                      focusedBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: greyColor),
                      ),
                      enabledBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: greyColor),
                      ),
                      labelText: 'Enter tanker name',
                      labelStyle: TextStyle(
                        color: greyColor, //<-- SEE HERE
                      ),
                    ),
                  ), //tanker name
                ),
                const SizedBox(
                  height: 5,
                ),
            /*    Container(
                  padding: const EdgeInsets.all(10),
                  child: TextFormField(
                    cursorColor: greyColor,
                    controller: tankerPhoneNumberController,
                    keyboardType: TextInputType.number,
                    maxLength: 10,
                    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: 5,
                ),

                Container(
                  padding: const EdgeInsets.all(10),
                  child: TextFormField(
                    cursorColor: greyColor,
                    controller: tankerAlternativePhoneNumberController,
                    keyboardType: TextInputType.number,
                    maxLength: 10,
                    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 alternative phone number',
                      labelStyle: TextStyle(
                        color: greyColor, //<-- SEE HERE
                      ),
                    ),
                  ),
                ), //alternative phone number
                const SizedBox(
                  height: 5,
                ),*/
                Visibility(
                  visible: true,
                  child: Container(
                    padding: const EdgeInsets.all(10),
                    child: TextFormField(
                      onChanged: (value) {
                        if (tankerCapacityController.text != '') {
                          setState(() {
                            isCapacityText = true;
                          });
                        } else {
                          setState(() {
                            isCapacityText = false;
                          });
                        }
                        value = '${AppSettings.formNum(
                          value.replaceAll(',', ''),
                        )}';
                        tankerCapacityController.value = TextEditingValue(
                          text: value,
                          selection: TextSelection.collapsed(
                            offset: value.length,
                          ),
                        );
                      },
                      cursorColor: greyColor,
                      controller: tankerCapacityController,
                      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
                SizedBox(
                  height: 5,
                ),




                Container(
                  padding: const EdgeInsets.fromLTRB(10, 10, 10, 0),
                  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.all(10),
                  child: TextFormField(
                    cursorColor: greyColor,
                    controller:tankerPriceController,
                    keyboardType: TextInputType.number,
                    maxLength: 10,
                    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
                      ),
                    ),
                  ),
                ), //alternative phone number
                const SizedBox(
                  height: 5,
                ),

/*
                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) {

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

                                    } else {

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



                                Visibility(
                                  visible: isDrinkingChecked,
                        child: Container(
                          height: 40,
                          width:200,
                          child:TextFormField(
                            cursorColor: greyColor,
                            controller: tankerDrinkingPriceController,
                            keyboardType: TextInputType.number,
                            *//*onSaved: (v){
                              waterPrice.add({'price': v.toString()});
                            },*//*
                            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) {

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

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

                                Visibility(
                                  visible: isBoreChecked,
                                  child: Container(
                                  height: 40,
                                  width:200,
                                  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),
                                    ),
                                  ),

                                ),)

                              ],
                            )
                          ],
                        ))
                ),
                SizedBox(
                  height: 20,
                ),*/
                Container(
                    width: MediaQuery.of(context).size.width * .99,
                    height: 50,
                    padding: const EdgeInsets.fromLTRB(10, 0, 10, 0),
                    child: ElevatedButton(
                      style: ElevatedButton.styleFrom(
                        primary: primaryColor, // background
                        onPrimary: Colors.white, // foreground
                      ),
                      onPressed: () async{

                        if (tankerNameController.text != '' &&
                            tankerCapacityController.text != '' &&
                            tankerPriceController.text != '') {
                       /*   waterPrice=[];
                          if(isDrinkingChecked){
                             waterPrice.add({'price': tankerDrinkingPriceController.text.toString()});
                          }
                          *//*else{
                            waterTypes.removeWhere((e) => e['price'].toString() == tankerDrinkingPriceController.text.toString());
                          }*//*

                          else if(isBoreChecked){
                            waterPrice.add({'price': tankerBorePriceController.text.toString()});
                          }
                          *//*else{
                            waterTypes.removeWhere((e) => e['price'].toString() == tankerBorePriceController.text.toString());
                          }*//*
*/

                          var payload = new Map<String, dynamic>();
                          payload["tankerName"] = tankerNameController.text.toString();
                         // payload["phoneNumber"] = tankerPhoneNumberController.text.toString();
                         // payload["alternative_phoneNumber"] = tankerAlternativePhoneNumberController.text.toString();
                          payload["capacity"] = tankerCapacityController.text.toString();
                         // payload["typeofwater"] = waterTypes;
                          payload["typeofwater"] =dropdownTypeOfWater.toString();
                          //payload["price"] = waterPrice;
                          payload["price"] = tankerPriceController.text.toString();
                          payload["supplier_address"] = AppSettings.supplierAddress;
                          payload["supplier_name"] = AppSettings.suppliername;

                          bool tankStatus = await AppSettings.addTankers(payload);

                          try {
                            if (tankStatus) {
                              AppSettings.longSuccessToast(
                                  "Tanker Created Successfully");
                              tankerNameController.text = '';
                              //tankerPhoneNumberController.text = '';
                              tankerCapacityController.text = '';
                              //tankerAlternativePhoneNumberController.text='';
                              tankerPriceController.text='';
                              //tankerDrinkingPriceController.text='';
                              //tankerBorePriceController.text='';
                              waterPrice=[];
                              waterTypes=[];
                              isDrinkingChecked=false;
                              isBoreChecked=false;
                              Navigator.pop(context);
                              await Navigator.push(
                                context,
                                MaterialPageRoute(
                                    builder: (context) =>  TankersView()),
                              );

                            }
                            else {
                              AppSettings.longFailedToast("Tanker Creation failed");
                            }
                          } catch (exception) {
                            print(exception);
                          }
                        } else {
                          AppSettings.longFailedToast("Please enter valid details");
                        }
                      },
                      child: const Text(
                        'Create Tanker',
                        style: TextStyle(
                          fontSize: 25,
                        ),
                      ),
                    )),

              ],
            ),
          )),
    );
  }
}
