import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:watermanagement/settings.dart';
import 'package:intl/intl.dart';
import 'package:flutter_cupertino_datetime_picker/flutter_cupertino_datetime_picker.dart';
import 'models/booking_requests_model.dart';
import 'models/getdeliveryboy_model.dart';

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

  @override
  State<BookingRequets> createState() => _BookingRequetsState();
}

class _BookingRequetsState extends State<BookingRequets> {
  List<BookingRequestsModel> BookingRequestsList = [];
  List<GetDeliveryboyDetailsModel> modeldeliveryboyList = [];
  bool isSereverIssuePending = false;
  bool isDataLoading = false;
  var dropdownAllDeliveryBoys;
  var selIOS;
  TextEditingController dateController = TextEditingController();
  Future<void> getBookingRequestsData() async {
    isDataLoading = true;

    try {
      var response = await AppSettings.getBookingRequests();

      setState(() {
        BookingRequestsList =
            ((jsonDecode(response)['data']) as List).map((dynamic model) {
          return BookingRequestsModel.fromJson(model);
        }).toList();
        isDataLoading = false;
      });
    } catch (e) {
      setState(() {
        isDataLoading = false;
        isSereverIssuePending = true;
      });
    }
  }
  Future<void> getAllDeliveryBoys() async {
    var response1= await AppSettings.getAllDeliverboy();
    print(response1);
    setState(() {
      modeldeliveryboyList =
          ((jsonDecode(response1)['data']) as List).map((dynamic model) {
            return GetDeliveryboyDetailsModel.fromJson(model);
          }).toList();
      dropdownAllDeliveryBoys=modeldeliveryboyList[0];
    });
  }
  @override
  void initState() {
    isDataLoading = true;
    getBookingRequestsData();
    getAllDeliveryBoys();
    super.initState();
  }

  Widget renderzUi() {
    if (BookingRequestsList.length != 0) {
      return Column(crossAxisAlignment: CrossAxisAlignment.end, children: [
        Expanded(
            child: ListView.builder(
                padding: EdgeInsets.all(0),
                itemCount: BookingRequestsList.length,
                itemBuilder: (BuildContext context, int index) {
                  return Card(
                    child: Padding(
                      padding: EdgeInsets.all(8),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Expanded(
                            child: Container(
                                width: MediaQuery.of(context).size.width * .70,
                                child: Row(
                                  children: [
                                    Column(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: [
                                        Text('Tanker Name:',
                                            style: labelTextStyle()),
                                        SizedBox(
                                          height: 10,
                                        ),
                                        Text('CustomerId:',
                                            style: labelTextStyle()),
                                        SizedBox(
                                          height: 10,
                                        ),
                                        Text('BookingId:',
                                            style: labelTextStyle()),
                                        SizedBox(
                                          height: 10,
                                        ),
                                        Text('Type Of Water:',
                                            style: labelTextStyle()),
                                        SizedBox(
                                          height: 10,
                                        ),
                                        Text('Capacity:',
                                            style: labelTextStyle()),
                                        SizedBox(
                                          height: 10,
                                        ),
                                        Text('Price:', style: labelTextStyle()),
                                        SizedBox(
                                          height: 10,
                                        ),
                                        Text('Payment Status:',
                                            style: labelTextStyle()),
                                        SizedBox(
                                          height: 10,
                                        ),
                                        Text('Order Status:',
                                            style: labelTextStyle()),
                                        SizedBox(
                                          height: 10,
                                        ),
                                        Text('Address:',
                                            style: labelTextStyle()),
                                      ],
                                    ),
                                    SizedBox(
                                      width: 10,
                                    ),
                                    Column(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: [
                                        SizedBox(
                                          height: 12,
                                        ),
                                        Text(
                                            BookingRequestsList[index]
                                                .tanker_name
                                                .toUpperCase(),
                                            style: valuesTextStyle()),
                                        SizedBox(
                                          height: 10,
                                        ),
                                        Text(
                                            BookingRequestsList[index]
                                                .customer_id
                                                .toUpperCase(),
                                            style: valuesTextStyle()),
                                        SizedBox(
                                          height: 10,
                                        ),
                                        Text(
                                            BookingRequestsList[index]
                                                .booking_id
                                                .toUpperCase(),
                                            style: valuesTextStyle()),
                                        SizedBox(
                                          height: 10,
                                        ),
                                        Text(
                                            BookingRequestsList[index]
                                                .type_of_water
                                                .toUpperCase(),
                                            style: valuesTextStyle()),
                                        SizedBox(
                                          height: 10,
                                        ),
                                        Text(
                                            BookingRequestsList[index]
                                                .capacity
                                                .toUpperCase(),
                                            style: valuesTextStyle()),
                                        SizedBox(
                                          height: 10,
                                        ),
                                        Text(
                                            BookingRequestsList[index]
                                                .price
                                                .toUpperCase(),
                                            style: valuesTextStyle()),
                                        SizedBox(
                                          height: 10,
                                        ),
                                        Text(
                                            BookingRequestsList[index]
                                                .payment_status
                                                .toUpperCase(),
                                            style: valuesTextStyle()),
                                        SizedBox(
                                          height: 10,
                                        ),
                                        Text(
                                            BookingRequestsList[index]
                                                .orderStatus
                                                .toUpperCase(),
                                            style: TextStyle(fontSize: 12,fontWeight: FontWeight.bold,color:BookingRequestsList[index].textColor )),
                                        SizedBox(
                                          height: 10,
                                        ),
                                        Container(

                                          width: MediaQuery.of(context).size.width * .50,
                                          child: Text(
                                              BookingRequestsList[index]
                                                  .customer_address
                                                  .toUpperCase(),
                                              style: valuesTextStyle()),
                                        )
                                      ],
                                    ),
                                  ],
                                )),
                          ),
                          /*Row(
                            children: [
                              Text('Tanker Name:',
                                  style: labelTextStyle()),
                              Text(
                                  BookingRequestsList[index]
                                      .tanker_name
                                      .toUpperCase(),
                                  style: valuesTextStyle()),

                            ],
                          ),*/
                          Visibility(
                             visible:BookingRequestsList[index].orderStatus.toString().toLowerCase()=='pending',
                              child: Column(
                            children: [
                              TextButton(
                                child: Text(
                                  'Accept',
                                  style: TextStyle(
                                      fontSize: 15,
                                      color:
                                          primaryColor /*FilteredList[index].text_color*/),
                                ),
                                onPressed: () async {

                                  return showDialog(
                                    context: context,
                                    barrierDismissible: false,
                                    builder: (BuildContext context) {
                                      return StatefulBuilder(
                                          builder: (BuildContext context, StateSetter setState) {
                                            return AlertDialog(
                                              title: const Text('Assign'),
                                              content: SingleChildScrollView(
                                                child: ListBody(
                                                  children: <Widget>[
                                                    Container(
                                                      padding: const EdgeInsets.fromLTRB(10, 10, 10, 0),
                                                      child: DropdownButtonFormField<GetDeliveryboyDetailsModel>(
                                                        // Initial Value
                                                        value: dropdownAllDeliveryBoys,
                                                        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: 'Select delivery boy',
                                                          labelStyle: TextStyle(
                                                            color: greyColor, //<-- SEE HERE
                                                          ),
                                                        ),

                                                        hint: Text('Select delivery boy'),
                                                        // Down Arrow Icon
                                                        icon: const Icon(Icons.keyboard_arrow_down),
                                                        items: modeldeliveryboyList
                                                            .map<DropdownMenuItem<GetDeliveryboyDetailsModel>>(
                                                                (value) => new DropdownMenuItem<GetDeliveryboyDetailsModel>(
                                                              value: value,
                                                              child: new Text(value.deliveryboy_name),
                                                            ))
                                                            .toList(),
                                                        onChanged: (GetDeliveryboyDetailsModel? newValue) {
                                                          setState(() {
                                                            dropdownAllDeliveryBoys = newValue;
                                                          });

                                                        },
                                                      ),
                                                    ),

                                                    SizedBox(
                                                      height: 05,
                                                    ),
                                                    Container(
                                                      padding: const EdgeInsets.all(10),
                                                      child: TextFormField(
                                                        cursorColor: greyColor,
                                                        enabled: false,
                                                        controller: dateController,
                                                        textCapitalization: TextCapitalization.characters,
                                                        decoration: const InputDecoration(
                                                          prefixIcon: Icon(
                                                            Icons.date_range,
                                                            color: greyColor,
                                                          ),
                                                          border: OutlineInputBorder(
                                                              borderSide: BorderSide(color: greyColor)),
                                                          focusedBorder: OutlineInputBorder(
                                                            borderSide: BorderSide(color: greyColor),
                                                          ),
                                                          enabledBorder: OutlineInputBorder(
                                                            borderSide: BorderSide(color: greyColor),
                                                          ),
                                                          labelText: 'Select date & time',
                                                          labelStyle: TextStyle(
                                                            color: greyColor, //<-- SEE HERE
                                                          ),
                                                        ),
                                                      ),
                                                    ),

                                                    SizedBox(
                                                      height: 05,
                                                    ),

                                                  ],
                                                ),
                                              ),
                                              actions: <Widget>[
                                                TextButton(
                                                  child: Text('cancel', style: textButtonStyle()),
                                                  onPressed: () {
                                                    Navigator.of(context).pop();
                                                  },
                                                ),
                                                TextButton(
                                                  child: Text('Accept', style: textButtonStyle()),
                                                  onPressed: () async{
                                                    var payload = new Map<String, dynamic>();
                                                    payload["supplierName"] =
                                                        AppSettings.suppliername;
                                                    payload["supplierId"] =
                                                        AppSettings.supplierId;
                                                    payload["customerId"] =
                                                        BookingRequestsList[index].customer_id;
                                                    payload["capacity"] =
                                                        BookingRequestsList[index].capacity;
                                                    payload["customer_address"] =
                                                        BookingRequestsList[index]
                                                            .customer_address;
                                                    payload["dateOfOrder"] =
                                                        BookingRequestsList[index].date_of_order;
                                                    payload["expectedDateOfDelivery"] =dateController.text.toString();
                                                    payload["action"] = "accept";
                                                    payload["price"] =
                                                        BookingRequestsList[index].price;
                                                    payload["delivery_agent"] = dropdownAllDeliveryBoys.deliveryboy_name;
                                                    payload["agent_mobile"] = dropdownAllDeliveryBoys.deliveryboy_phone;
                                                    payload["agent_alternative_mobile"] = dropdownAllDeliveryBoys.deliveryboy_alternativeContactNumber;

                                                    bool requestStatus =
                                                        await AppSettings.acceptBookingRequests(
                                                        BookingRequestsList[index].booking_id,
                                                        payload);

                                                    if (requestStatus) {
                                                      Navigator.of(context).pop();
                                                      AppSettings.longSuccessToast(
                                                          "Booking Accepted");
                                                      await getBookingRequestsData();
                                                      // getAllSuppliersData();
                                                      //await getConnectedSuppliersData();
                                                      //await getPendingSuppliersData();

                                                    } else {}
                                                  },
                                                ),


                                                IconButton(
                                                    onPressed: () async {
                                                        DatePicker.showDatePicker(
                                                          context,
                                                          dateFormat: 'dd MMMM yyyy HH:mm',
                                                          initialDateTime: DateTime.now(),
                                                          minDateTime:DateTime.now(),
                                                          maxDateTime: DateTime.now().add(Duration(days: 15)),
                                                          onMonthChangeStartWithFirstDate: true,
                                                          pickerMode: DateTimePickerMode.datetime,
                                                          pickerTheme: DateTimePickerTheme(
                                                            // backgroundColor: Colors.white,
                                                            cancelTextStyle: labelTextStyle(),
                                                            confirmTextStyle: labelTextStyle(),
                                                            // showTitle: true,
                                                            //title: Text('Pick date and time'),
                                                            itemTextStyle: valuesTextStyle(),
                                                          ),
                                                          onConfirm: (dateTime, List<int> index)async {
                                                            DateTime selectdate = dateTime;
                                                            setState(() {
                                                              selIOS = DateFormat('dd-MMM-yyyy - HH:mm').format(selectdate);
                                                            });

                                                            if(selIOS!=''){
                                                              setState(() {
                                                                dateController.text=selIOS.toString();
                                                              });
                                                            }
                                                            else {
                                                              AppSettings.longFailedToast('please select date');
                                                            }
                                                          },
                                                        );
                                                    },
                                                    icon: Icon(
                                                      Icons.calendar_month,
                                                      color: primaryColor,
                                                    ))



                                              ],
                                            );
                                          });
                                    },
                                  );




                                },
                              ),
                              TextButton(
                                child: Text(
                                  'Reject',
                                  style: TextStyle(
                                      fontSize: 15,
                                      color:
                                          primaryColor /*FilteredList[index].text_color*/),
                                ),
                                onPressed: () async {
                                  var payload = new Map<String, dynamic>();
                                  payload["supplierName"] =
                                      AppSettings.suppliername;
                                  payload["supplierId"] =
                                      AppSettings.supplierId;
                                  payload["customerId"] =
                                      BookingRequestsList[index].customer_id;
                                  payload["capacity"] =
                                      BookingRequestsList[index].capacity;
                                  payload["customer_address"] =
                                      BookingRequestsList[index]
                                          .customer_address;
                                  payload["dateOfOrder"] =
                                      BookingRequestsList[index].date_of_order;
                                  payload["action"] = "reject";
                                  payload["price"] =
                                      BookingRequestsList[index].price;
                                  payload["delivery_agent"] = '';
                                  payload["agent_mobile"] = '';
                                  payload["agent_alternative_mobile"] = '';

                                  bool requestStatus =
                                  await AppSettings.acceptBookingRequests(
                                      BookingRequestsList[index].booking_id,
                                      payload);

                                  if (requestStatus) {
                                    AppSettings.longSuccessToast(
                                        "Booking Rejected");
                                    await getBookingRequestsData();
                                    // getAllSuppliersData();
                                    //await getConnectedSuppliersData();
                                    //await getPendingSuppliersData();

                                  } else {}
                                },
                              ),
                            ],
                          ))
                        ],
                      ),
                    ),
                  );
                })),
      ]);
    } 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('No Data Found'),
            SizedBox(
              height: 20,
            ),
          ],
        ),
      ));
    }
  }

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