import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../../../../../../Controller/Dashboard/Pickup/Tabs/Tenantcustomers/Customeraddress/Customeraddresscontroller.dart';
import '../../../../../../../Helper/Constants/Assetconstants.dart';
import '../../../../../../../Helper/Constants/Colorconstants.dart';
import '../../../../../../../Helper/custombutton.dart';
import '../../../../../../../Helper/customederaction.dart';
import '../../../../../../../Helper/toast.dart';
import '../../../../../../../Model/Response/Customers/GetCustomerById/GetCustomerByTenantId.dart';
import '../../../../../../../Model/Response/Getcustomeraddress/GetCustomerAddress.dart';
import '../../../../../Createorderview.dart';




class CustomerPickupAddressView extends StatelessWidget {
  final GetCustomerByTenantIdDetails? data;


  CustomerPickupAddressView({super.key, required this.data});

  PickupCustomerAddressController pickupCustomerAddressController = Get.put(PickupCustomerAddressController());


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: ColorConstants.primaryColor,
        elevation: 0.3,
        leading: Padding(
          padding: const EdgeInsets.all(5.0),
          child:InkWell(
              onTap: (){
                pickupCustomerAddressController.deliveryAddressList = false;
                Get.back();
              },
              child: Icon(Icons.reply,size: 30,color: ColorConstants.secondaryColor,)),
        ),
        title: Text('Pickup Address'),
        titleSpacing: 0,
        actions: [
          InkWell(
            onTap: ()async{
              // if (savedAddressController.resultPosition != null) {
              //   var locationResult = await Get.to(AddCustomerAddressMap( long: savedAddressController.resultPosition!.longitude, lat: savedAddressController.resultPosition!.latitude,));
              //   if (locationResult != null) {
              //     savedAddressController.setLocationValues(locationResult);
              //   }
              // }
              pickupCustomerAddressController.deliveryAddressList = true;
              pickupCustomerAddressController.addressController.clear();
              pickupCustomerAddressController.suburbController.clear();
              pickupCustomerAddressController.cityController.clear();
              pickupCustomerAddressController.stateController.clear();
              pickupCustomerAddressController.postCodeController.clear();
              pickupCustomerAddressController.doornoController.clear();
              pickupCustomerAddressController.landmarkController.clear();

              pickupCustomerAddressController.update();

            },
            child: CircleAvatar(
                radius: 20,
                backgroundColor: ColorConstants.secondaryColor,
                child: Icon(Icons.location_on,color: ColorConstants.primaryColor,size: 25,)),
          ),
          SizedBox(width: 20,)
        ],

      ),
      backgroundColor: Colors.grey[100],
      body: GetBuilder<PickupCustomerAddressController>(
          initState: (_){
            pickupCustomerAddressController.loader = true;
            pickupCustomerAddressController.customerId =data?.customerid;
            pickupCustomerAddressController.customerName ="${data?.firstname}"+ "${data?.lastname}";
            pickupCustomerAddressController.customerContactNo =data?.contactno;
            pickupCustomerAddressController.customerAddressInfo = data;
            pickupCustomerAddressController.getDetails();
            pickupCustomerAddressController.getCustomerAddress();
          },
          builder: (controller) {
            print("deliveryAddressListbool...............${controller.deliveryAddressList}");
            return Column(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                SizedBox(height: 10,),
                addAddress(),
                Padding(
                    padding: EdgeInsets.only(left: 10, top: 10, bottom: 5),
                    child: Text(
                      "Select delivery address :",
                      style: TextStyle(
                          fontWeight: FontWeight.bold,
                          color: ColorConstants.primaryColor,
                          fontSize: 16),
                      textAlign: TextAlign.start,
                    )),
                controller.deliveryAddressList == true
                    ? Expanded(
                    child: ListView(
                      children: [
                        Column(
                          children: [
                            SizedBox(
                              height: 20,
                            ),
                            addressWidget(),
                            SizedBox(
                              height: 10,
                            ),
                            suburb(),
                            SizedBox(
                              height: 10,
                            ),
                            city(),
                            SizedBox(
                              height: 10,
                            ),
                            state(),
                            SizedBox(
                              height: 10,
                            ),
                            postalCode(),
                            SizedBox(
                              height: 10,
                            ),
                            doorNo(),
                            SizedBox(
                              height: 10,
                            ),
                            landmark(),
                          ],
                        )
                      ],
                    ))
                    : Expanded(
                    child: savedAddressDetailsList()
                ),
                SizedBox(height: 2),
                controller.deliveryAddressList == true
                    ? submit()
                    : Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [

                    proceed(),
                  ],
                )
              ],
            );
          }
      ),
      // floatingActionButton:savedAddressController.deliveryAddressList == false
      //     ? FloatingActionButton(
      //   onPressed: () async{
      //     if (savedAddressController.resultPosition != null) {
      //       var locationResult = await Get.to(AddCustomerAddressMap( long: savedAddressController.resultPosition!.longitude, lat: savedAddressController.resultPosition!.latitude,));
      //       if (locationResult != null) {
      //         savedAddressController.setLocationValues(locationResult);
      //       }
      //     }
      //   },
      //   child: Icon(
      //     Icons.add,
      //     color: ColorConstants.secondaryColor,
      //   ),
      //   backgroundColor: ColorConstants.primaryColor,
      // ):Container(),

    );
  }

  addAddress() {
    return Padding(
      padding: const EdgeInsets.only(top: 0,left: 10,right: 10),
      child: Card(
        elevation: 0,
        surfaceTintColor: ColorConstants.secondaryColor,
        child: Row(
          children: [
            Container(
              height: Get.height*0.12,
              width: Get.width*0.3,
              decoration: BoxDecoration(borderRadius: BorderRadius.circular(3),color: ColorConstants.primaryColor1),
              child: Icon(Icons.delivery_dining,size: 55,color: ColorConstants.darkGreyColor),
            ),
            Container(
              height: Get.height*0.12,
              width: Get.width*0.6,
              // decoration: BoxDecoration(borderRadius: BorderRadius.circular(10),color: ColorConstants.secondaryColor),
              child: Padding(
                padding: const EdgeInsets.only(top: 14,left: 10),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Icon(Icons.person,color: ColorConstants.primaryColor,size: 25,),
                        SizedBox(width: 5,),
                        Expanded(child: Text('${data?.firstname} ${data?.lastname}',style:TextStyle(fontSize: 18,color: ColorConstants.darkGreyColor,fontWeight: FontWeight.bold),maxLines: 1,overflow: TextOverflow.ellipsis)),
                      ],
                    ),
                    // SizedBox(height: 4,),
                    // Row(
                    //   children: [
                    //     Icon(Icons.location_on,color: ColorConstants.primaryColor,size: 20,),
                    //     SizedBox(width: 5,),
                    //     Expanded(child: Padding(
                    //       padding: const EdgeInsets.only(top: 5),
                    //       child: Text('${data[0].address}',style:TextStyle(fontSize: 15,color: ColorConstants.darkGreyColor,fontWeight: FontWeight.bold),maxLines: 2,overflow: TextOverflow.ellipsis,),
                    //     ),),
                    //   ],
                    // ),
                    SizedBox(height: 7,),

                    Row(
                      children: [
                        Padding(
                          padding: const EdgeInsets.only(left: 5),
                          child: Icon(Icons.phone,color: ColorConstants.primaryColor,size: 25,),
                        ),
                        SizedBox(width: 5,),
                        Text('${data?.contactno}',style:TextStyle(fontSize: 18,color: ColorConstants.darkGreyColor,fontWeight: FontWeight.bold)),
                      ],
                    ),

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

  addressWidget() {
    return GetBuilder<PickupCustomerAddressController>(
        builder: (controller) {
          return Column(
            children: [
              Container(
                padding: EdgeInsets.only(top: 0),
                height: Get.height*0.08,
                width: Get.width*0.9,
                // decoration: BoxDecoration(
                //   color: secondaryColor,
                //   borderRadius: BorderRadius.circular(10),
                // ),
                child:
                TextField(
                  style: TextStyle(
                    fontSize: 14,fontWeight: FontWeight.bold,
                    // color: Colors.grey[400],
                  ),
                  controller: controller.addressController,
                  onChanged: (text) => controller.onSearchTextChanged(text),

                  decoration: InputDecoration(
                      prefixIcon:Icon( Icons.location_on,color: ColorConstants.primaryColor,) ,
                      suffixIcon: InkWell(
                          onTap: (){
                            controller.addressController.clear();
                            controller.suburbController.clear();
                            controller.cityController.clear();
                            controller.stateController.clear();
                            controller.postCodeController.clear();
                          },
                          child: Icon(Icons.close,color: Colors.red,)),
                      // suffixIcon: InkWell(
                      //   onTap: ()async{
                      //     if (savedAddressController.resultPosition != null) {
                      //       var locationResult = await Get.to(AddCustomerAddressMap( long: savedAddressController.resultPosition!.longitude, lat: savedAddressController.resultPosition!.latitude,));
                      //       if (locationResult != null) {
                      //         savedAddressController.setLocationValues(locationResult);
                      //       }
                      //     }
                      //   },
                      //     child: Icon(Icons.edit,color: ColorConstants.primaryColor,)),
                      enabledBorder: OutlineInputBorder(
                        borderSide: BorderSide(
                          color: Colors.grey[400]!,
                          width: 2,
                        ),
                      ),
                      focusedBorder: OutlineInputBorder(
                        borderSide: BorderSide(
                          color: ColorConstants.primaryColor,
                          width: 2,
                        ),
                      ),

                      labelText: 'Address',
                      labelStyle: TextStyle(color: ColorConstants.primaryColor)),
                ),

              ),
              SizedBox(height: 8,),

              controller.predictions.isNotEmpty?Container(
                height: Get.height*0.20,
                width: Get.width,
                decoration: BoxDecoration(color: ColorConstants.secondaryColor),
                child: Obx(() {
                  return ListView.builder(
                    itemCount: controller.predictions.length,
                    itemBuilder: (context, index) {
                      final prediction =
                      controller.predictions[index]['description'];
                      return ListTile(
                        title: Text(prediction),
                        onTap: () {
                          final placeId =
                          controller.predictions[index]['place_id'];
                          controller.getPlaceDetails(placeId,prediction);
                          controller.searchController.clear();
                          controller.predictions.clear();
                          FocusScope.of(context).unfocus();
                        },
                      );
                    },
                  );

                }),):SizedBox(),

            ],
          );

        }
    );
  }

  Widget suburb(){
    return Container(
      height: Get.height*0.07,
      width: Get.width*0.9,
      // decoration: BoxDecoration(
      //   color: secondaryColor,
      //   borderRadius: BorderRadius.circular(10),
      // ),
      child: TextFormField(
        style: TextStyle(fontSize: 15,fontWeight: FontWeight.bold),
        decoration: CustomDecoration.textFieldStyle(
            labelTextStr: "Suburb",
            prefixIcon: Icon(
              Icons.location_on,
              color: ColorConstants.primaryColor,
            )),
        controller:pickupCustomerAddressController.suburbController,
        onEditingComplete: () {
          var context = Get.context;
          FocusScope.of(context!).requestFocus(FocusNode());
        },
      ),
    );

  }

  Widget city(){
    return Container(
      height: Get.height*0.07,
      width: Get.width*0.9,
      // decoration: BoxDecoration(
      //   color: secondaryColor,
      //   borderRadius: BorderRadius.circular(10),
      // ),
      child: TextFormField(
        style: TextStyle(fontSize: 15,fontWeight: FontWeight.bold),
        decoration: CustomDecoration.textFieldStyle(
            labelTextStr: "City",
            prefixIcon: Icon(
              Icons.location_city,
              color:  ColorConstants.primaryColor,
            )),
        controller:pickupCustomerAddressController.cityController,
        onEditingComplete: () {
          var context = Get.context;
          FocusScope.of(context!).requestFocus(FocusNode());
        },
      ),
    );

  }

  Widget state(){
    return Container(
      height: Get.height*0.07,
      width: Get.width*0.9,
      // decoration: BoxDecoration(
      //   color: secondaryColor,
      //   borderRadius: BorderRadius.circular(10),
      // ),
      child: TextFormField(
        style: TextStyle(fontSize: 15,fontWeight: FontWeight.bold),
        decoration: CustomDecoration.textFieldStyle(
            labelTextStr: "State",
            prefixIcon: Icon(
              Icons.account_balance,
              color:  ColorConstants.primaryColor,
            )),
        controller:pickupCustomerAddressController.stateController,
        onEditingComplete: () {
          var context = Get.context;
          FocusScope.of(context!).requestFocus(FocusNode());
        },
      ),
    );

  }

  Widget postalCode(){
    return Container(
      height: Get.height*0.07,
      width: Get.width*0.9,
      // decoration: BoxDecoration(
      //   color: secondaryColor,
      //   borderRadius: BorderRadius.circular(10),
      // ),
      child: TextFormField(
        style: TextStyle(fontSize: 15,fontWeight: FontWeight.bold),
        decoration: CustomDecoration.textFieldStyle(
            labelTextStr: "PostCode",
            prefixIcon: Icon(
              Icons.local_post_office,
              color:  ColorConstants.primaryColor,
            )),
        controller:pickupCustomerAddressController.postCodeController,
        onEditingComplete: () {
          var context = Get.context;
          FocusScope.of(context!).requestFocus(FocusNode());
        },
      ),
    );

  }

  Widget landmark(){
    return Container(
      height: Get.height*0.07,
      width: Get.width*0.9,
      // decoration: BoxDecoration(
      //   color: secondaryColor,
      //   borderRadius: BorderRadius.circular(10),
      // ),
      child: TextFormField(
        style: TextStyle(fontSize: 15,fontWeight: FontWeight.bold),
        decoration: CustomDecoration.textFieldStyle(
            labelTextStr: "LandMark",
            prefixIcon: Icon(
              Icons.home,
              color:  ColorConstants.primaryColor,
            )),
        controller:pickupCustomerAddressController.landmarkController,
        onEditingComplete: () {
          var context = Get.context;
          FocusScope.of(context!).requestFocus(FocusNode());
        },
      ),
    );

  }

  Widget doorNo(){
    return Container(
      height: Get.height*0.07,
      width: Get.width*0.9,
      // decoration: BoxDecoration(
      //   color: secondaryColor,
      //   borderRadius: BorderRadius.circular(10),
      // ),
      child: TextFormField(
        style: TextStyle(fontSize: 15,fontWeight: FontWeight.bold),
        decoration: CustomDecoration.textFieldStyle(
            labelTextStr: "Doorno",
            prefixIcon: Icon(
              Icons.door_back_door,
              color: ColorConstants.primaryColor,
            )),
        controller:pickupCustomerAddressController.doornoController,

        // focusNode: individualNameNode,
        onEditingComplete: () {
          var context = Get.context;
          FocusScope.of(context!).requestFocus(FocusNode());
        },
      ),
    );

  }

  savedAddressDetailsList() {
    return Padding(
      padding: const EdgeInsets.only(top: 10,left: 20),
      child: GetBuilder<PickupCustomerAddressController>(
          builder: (controller) {
            return controller.getCustomeraddress.isEmpty && !controller.loader == true
                ? Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Image(
                      height: 160,
                      width: 160,
                      image: AssetImage(AssetConstants.NoRecords),
                    ),
                    SizedBox(
                      height: 8,
                    ),
                    Text(
                      "No delivery address available",
                      style: TextStyle(
                          color: Colors.grey[600],
                          fontSize: 18),
                    ),
                  ],
                )):controller.loader?Center(child: CircularProgressIndicator(color: ColorConstants.primaryColor)):

            Container(
              width: Get.width*0.90,
              child: ListView.separated(
                itemCount: controller.getCustomeraddress.length,
                padding: EdgeInsets.only(top: 4),
                itemBuilder: (BuildContext context, int index) {
                  return addressCard(controller.getCustomeraddress[index], index);
                },
                separatorBuilder: (BuildContext context, int index) =>
                    Container(height: 8, color: Colors.grey[100]),
              ),
              // color: Colors.white,

            );
          }
      ),
    );
  }

  addressCard(CustomerAddressDetail models, int index) {
    return GetBuilder<PickupCustomerAddressController>(
        builder: (controller) {
          return InkWell(
            onTap: (){
              controller.selectedAddressIndex = index;
              controller.locationId = models.locationid!;
              controller.address = models.address??'';
              controller.addressController.text =models.address!;
              controller.latitude = models.latitude;
              controller.longitude = models.longitude;
              // controller.changeCustomeraddress.add(controller.mSelectedAddressIndex[index]);
              controller.update();
              print('locationIdonChanged ${controller.locationId}');
              print('addressControlleronChanged ${controller.addressController.text}');
              print('addressControlleronChanged ${controller.selectedAddressIndex}');
              print('latitudeControlleronChanged ${ controller.latitude}');
              print('longitudeControlleronChanged ${ controller.longitude}');
            },
            child: Container(
                padding: EdgeInsets.only(top: 10,bottom: 10),
                decoration: BoxDecoration(color: ColorConstants.secondaryColor,borderRadius: BorderRadius.circular(5)),
                child: ListTile(
                  // leading: Padding(
                  //   padding: const EdgeInsets.fromLTRB(0, 8, 8, 8),
                  //   child: Icon(
                  //     Icons.my_location,
                  //     size: 25,
                  //     color: Colors.grey,
                  //   ),
                  // ),
                  trailing: InkWell(
                    onTap: (){
                      controller.selectedAddressIndex = index;
                      controller.locationId = models.locationid!;
                      controller.addressController.text =models.address!;
                      controller.latitude = models.latitude;
                      controller.longitude = models.longitude;
                      // controller.changeCustomeraddress.add(controller.mSelectedAddressIndex[index]);
                      controller.update();
                      print('locationIdonChanged ${controller.locationId}');
                      print('addressControlleronChanged ${controller.addressController.text}');
                      print('addressControlleronChanged ${controller.selectedAddressIndex}');
                      print('latitudeControlleronChanged ${ controller.latitude}');
                      print('longitudeControlleronChanged ${ controller.longitude}');
                    },
                    child: CircleAvatar(
                      radius: 12,
                      backgroundColor:controller.selectedAddressIndex==index?Colors.green:Colors.grey[300],
                      child: Icon(Icons.check,color: ColorConstants.secondaryColor,size: 20),
                    ),
                  ),
                  title: Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          Icon(Icons.location_city,size: 20,color: ColorConstants.primaryColor,),
                          SizedBox(width: 4,),
                          Text('${controller.getCustomeraddress[index].suburb}',
                              style: TextStyle(fontSize: 14, fontWeight: FontWeight.bold,color: ColorConstants.darkGreyColor)),
                        ],
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Padding(
                            padding: const EdgeInsets.only(top: 5),
                            child: Icon(Icons.location_on,size: 20,color: ColorConstants.primaryColor,),
                          ),
                          SizedBox(width: 4,),
                          Padding(
                            padding: const EdgeInsets.only(top: 5),
                            child: Container(
                              width: Get.width*0.59,
                              child: Text('${controller.getCustomeraddress[index].address}',
                                  maxLines: 3,
                                  overflow: TextOverflow.ellipsis,
                                  style: TextStyle(fontSize: 14, fontWeight: FontWeight.bold,color: ColorConstants.darkGreyColor)),
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
                // color: Colors.white,
                margin: EdgeInsets.only(bottom: 2)),
          );
        }
    );
  }

  submit() {
    return Center(
      child: Padding(
        padding: const EdgeInsets.only(bottom: 30),
        child: Center(
            child:  RoundedButton(
              onPressed: () {
                pickupCustomerAddressController.describeValidation();
              },
              color:ColorConstants.primaryColor,
              title: 'Submit',
              controller: pickupCustomerAddressController.submitBtnController,
              textStyle: const TextStyle(
                  fontSize: 18,
                  fontFamily: "Lato",
                  color: Colors.white,
                  fontWeight: FontWeight.bold),
              height: Get.height*0.06,
              width: Get.width*0.8,
            )
        ),

      ),
    );
  }

  proceed() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Center(
            child: Padding(
              padding: const EdgeInsets.only(bottom: 20,top: 10),
              child:  Center(
                  child:  RoundedButton(
                    onPressed: () {
                      if(pickupCustomerAddressController.selectedAddressIndex!=-1){
                        pickupCustomerAddressController.selectedAddressIndex =-1;
                        // Get.to(OrderDetailsView(data:data));
                        pickupCustomerAddressController.btnController.success();
                          Get.to(CreateOrderView(pickUpData: data,isDashboard: false,));
                        pickupCustomerAddressController.btnController.reset();
                      }
                      else{
                        print('Please Select delivery address');
                        Toast.showToast('Please Select delivery address',);

                        pickupCustomerAddressController.btnController.reset();
                      }
                      pickupCustomerAddressController.update();

                    },
                    color:ColorConstants.primaryColor,
                    title: 'Proceed',
                    controller: pickupCustomerAddressController.btnController,
                    textStyle: const TextStyle(
                        fontSize: 18,
                        fontFamily: "Lato",
                        color: Colors.white,
                        fontWeight: FontWeight.bold),
                    height: Get.height*0.06,
                    width: Get.width*0.8,
                  )
              ),


            )),
        // Padding(
        //   padding: const EdgeInsets.only(top: 5,left: 20),
        //   child: FloatingActionButton(
        //     onPressed: () async{
        //       if (savedAddressController.resultPosition != null) {
        //         var locationResult = await Get.to(AddCustomerAddressMap( long: savedAddressController.resultPosition!.longitude, lat: savedAddressController.resultPosition!.latitude,));
        //         if (locationResult != null) {
        //           savedAddressController.setLocationValues(locationResult);
        //         }
        //       }
        //     },
        //     child: Icon(
        //       Icons.location_on,
        //       color: ColorConstants.secondaryColor,
        //     ),
        //     backgroundColor: ColorConstants.primaryColor,
        //   ),
        // )
      ],
    );
  }

}
