import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:watermanagement/model/getdeliveryboy_model.dart';
import 'package:watermanagement/settings.dart';
import 'package:intl/intl.dart';
import 'order_tracking_page.dart';


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

  @override
  State<DelivryBookingData> createState() => _DelivryBookingDataState();
}

class _DelivryBookingDataState extends State<DelivryBookingData> with TickerProviderStateMixin {
  bool isSupplierDataLoading=false;
  bool isSereverIssue = false;
  bool isSereverIssueConnected = false;
  bool isSereverIssuePending = false;
  String dropdownTypeOfPayment = 'Cash';
  String dueAmount = '';
  var typeOfPaymentItems = [
    'Cash',
    'Online',
  ];
  TextEditingController amountPaidController = TextEditingController();

  List<GetDeliveryboyDetailsModel> bookingDataList = [];
  List<GetDeliveryboyDetailsModel> completedOrdersList = [];
  List<GetDeliveryboyDetailsModel> activeOrdersList = [];
  bool isLoading=false;
  late TabController _controller;


  final List<Tab> topTabs = <Tab>[
    Tab(
        child: Text('Active Orders',style: TextStyle(fontSize: 15),)
    ),
    Tab(
        child: Text('Completed Orders',style: TextStyle(fontSize: 15),)
    ),
  ];

  Future<void> getBokkingsData() async {
    isLoading = true;
    try {
      var response = await AppSettings.getdeliveryboybookings();
      setState(() {
        bookingDataList =
            ((jsonDecode(response)['data']) as List).map((dynamic model) {
              return GetDeliveryboyDetailsModel.fromJson(model);
            }).toList();
        activeOrdersList=bookingDataList.where((product) => product.orderStatus.toString().toLowerCase()!='delivered').toList();
        activeOrdersList=activeOrdersList.reversed.toList();
        completedOrdersList=bookingDataList.where((product) => product.orderStatus.toString().toLowerCase()=='delivered').toList();
        completedOrdersList=completedOrdersList.reversed.toList();
        isLoading = false;
      });


    } catch (e) {
      setState(() {
        isLoading = false;
        isSereverIssueConnected = true;
      });
    }
  }



  @override
  void initState() {
    // TODO: implement initState
    _controller = TabController(vsync: this, length:2);
    getBokkingsData();
    super.initState();
  }


  showFinishOrderDialog(var obj) async {


    return showDialog(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return StatefulBuilder(
              builder: (BuildContext context, StateSetter setState) {
                return AlertDialog(
                  title: Text('Finish Order'),
                  content: SingleChildScrollView(
                      child: ListBody(
                        children: [
                          Container(
                            padding: const EdgeInsets.fromLTRB(10, 10, 10, 0),
                            child: Text(obj.bookingid),
                          ),
                          SizedBox(
                            height: 10,
                          ),
                          Container(
                            padding: const EdgeInsets.fromLTRB(10, 10, 10, 0),
                            child: Text(obj.price),
                          ),
                          SizedBox(
                            height: 10,
                          ),
                          Container(
                            padding: const EdgeInsets.fromLTRB(10, 10, 10, 0),
                            child: DropdownButtonFormField<String>(
                              // Initial Value
                              value: dropdownTypeOfPayment,
                              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: 'Choose Type of Payment',
                                labelStyle: TextStyle(
                                  color: greyColor, //<-- SEE HERE
                                ),
                              ),

                              hint: Text('Select Type of payment'),
                              // Down Arrow Icon
                              icon: const Icon(Icons.keyboard_arrow_down),
                              items: typeOfPaymentItems
                                  .map<DropdownMenuItem<String>>(
                                      (value) => new DropdownMenuItem<String>(
                                    value: value,
                                    child: new Text(value),
                                  ))
                                  .toList(),
                              onChanged: (String? newValue) {
                                setState(() {
                                  dropdownTypeOfPayment = newValue!;
                                });

                              },
                            ),
                          ),
                          SizedBox(
                            height: 10,
                          ),
                          Container(
                            padding: const EdgeInsets.all(10),
                            child: TextFormField(
                              cursorColor: greyColor,
                              controller: amountPaidController,
                              textCapitalization: TextCapitalization.sentences,
                              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: 'Amount Paid ',
                                labelStyle: TextStyle(
                                  color: greyColor, //<-- SEE HERE
                                ),
                              ),
                              onChanged: (string) {
                                string = '${AppSettings.formNum(
                                  string.replaceAll(',', ''),
                                )}';
                                amountPaidController.value = TextEditingValue(
                                  text: string,
                                  selection: TextSelection.collapsed(
                                    offset: string.length,
                                  ),
                                );
                                setState(() {
                                  if(amountPaidController.text.length>0){
                                    dueAmount=(int.parse(obj.price)-int.parse(amountPaidController.text.replaceAll(',', ''))).toString();
                                  }
                                  else{
                                    dueAmount=obj.price.toString();
                                  }
                                });
                              },

                            ),
                          ),
                          Visibility(
                            visible: amountPaidController.text!='',
                            child: Container(
                            padding: const EdgeInsets.fromLTRB(10, 10, 10, 0),
                            child: Text("Due:$dueAmount"),
                          ),)
                        ]
                      )),
                  actions: <Widget>[
                    TextButton(
                      child: Text('No', style: textButtonStyle()),
                      onPressed: () {
                        Navigator.of(context).pop();
                        amountPaidController.clear();
                      },
                    ),
                    TextButton(
                      child: Text('Finish Order', style: textButtonStyle()),
                      onPressed: () async {

                        if(amountPaidController.text!=''){
                          String x='';
                          x =amountPaidController.text. replaceAll(',', '');

                          if(int.parse(x)<=int.parse(obj.price)){
                            var payload = new Map<String, dynamic>();

                            final DateTime now = DateTime.now();
                            final DateFormat formatter = DateFormat('dd-MMM-yyyy - HH:mm');

                            final String formatted = formatter.format(now);
                            print(formatted);
                            
                        payload["amount_paid"] = amountPaidController.text.toString();
                        payload["payment_mode"] = dropdownTypeOfPayment.toString().toLowerCase();
                        payload["orderStatus"] = 'delivered';
                        payload["deliveredDate"] = formatted;

                            bool updateStatus = await AppSettings.deliveryboyFinishOrder(obj.bookingid,payload);
                            
                            if(updateStatus){
                              AppSettings.longSuccessToast('Status updated');
                              Navigator.of(context).pop();
                              amountPaidController.clear();
                              getBokkingsData();
                            }
                            else{
                              AppSettings.longFailedToast('failed to update the status');
                              Navigator.of(context).pop();
                              amountPaidController.clear();
                            }


                          }
                          else{
                            AppSettings.longFailedToast('Please enter valid amount paid');
                          }

                        }
                        else{
                          AppSettings.longFailedToast('Please provide amount paid');
                        }



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


  Widget activeOrders(){
    if (activeOrdersList.length != 0) {
      return ListView.builder(
          padding: EdgeInsets.all(8),
          itemCount: activeOrdersList.length,
          itemBuilder: (BuildContext context, int index) {
            return Card(
              child: Padding(
                padding: EdgeInsets.all(8),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Container(
                      // width: MediaQuery.of(context).size.width * .75,
                      child: Column(
                        mainAxisAlignment:
                        MainAxisAlignment.spaceBetween,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            children: [
                              Text('TankerName :',
                                  style: labelTextStyle()),
                              SizedBox(
                                width: 5.0,
                              ),
                              Text(
                                  activeOrdersList[index]
                                      .tankerName
                                      .toUpperCase(),
                                  style: valuesTextStyle()),
                            ],
                          ),
                          Row(
                            children: [
                              Text('Bookingid :',
                                  style: labelTextStyle()),
                              SizedBox(
                                width: 5.0,
                              ),
                              Text(
                                  activeOrdersList [index]
                                      .bookingid
                                      .toString(),
                                  style: valuesTextStyle()),
                            ],
                          ),
                          Row(
                            children: [
                              Text('SupplierId :',
                                  style: labelTextStyle()),
                              SizedBox(
                                width: 5.0,
                              ),
                              Text(activeOrdersList[index].supplierId,
                                  style: valuesTextStyle()),
                            ],
                          ),
                          Row(
                            children: [
                              Text('DateOfOrder :',
                                  style: labelTextStyle()),
                              SizedBox(
                                width: 5.0,
                              ),
                              Text(activeOrdersList[index].dateOfOrder,
                                  style: valuesTextStyle()),
                            ],
                          ),
                          Row(
                            children: [
                              Text('Typeofwater :',
                                  style: labelTextStyle()),
                              SizedBox(
                                width: 5.0,
                              ),
                              Text(activeOrdersList[index].typeofwater,
                                  style: valuesTextStyle()),
                            ],
                          ),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            crossAxisAlignment:
                            CrossAxisAlignment.start,
                            children: [
                              Column(
                                children: [
                                  IconButton(
                                    iconSize: 30,
                                    icon: const Icon(
                                      Icons.phone,
                                      color: primaryColor,
                                    ),
                                    onPressed: () async {
                                      final Uri _phoneUri = Uri(
                                          scheme: "tel",
                                          path: activeOrdersList[index]
                                              .delivery_agent_mobile);
                                      try {
                                        await launch(
                                            _phoneUri.toString());
                                      } catch (error) {
                                        throw ("Cannot dial");
                                      }
                                    },
                                  ),
                                  Text(
                                    'Call now',
                                    style: iconBelowTextStyle(),
                                  ),
                                ],
                              ),
                              SizedBox(
                                width: 30,
                              ),
                              Column(
                                children: [
                                  IconButton(
                                    iconSize: 30,
                                    icon: const Icon(
                                      Icons.start,
                                      color: primaryColor,
                                    ),
                                    onPressed: () {

                                      Navigator.push(
                                          context,
                                          new MaterialPageRoute(
                                              builder: (__) => new OrderTrackingPage(lat:activeOrdersList[index].lat,lng:activeOrdersList[index].lng)));

                                     /* Navigator.push(
                                        context,
                                        MaterialPageRoute(builder: (context) => OrderTrackingPage()),
                                      );*/


                                    },
                                  ),
                                  Text(
                                    'Start Trip',
                                    style: iconBelowTextStyle(),
                                  ),
                                ],
                              ),
                              SizedBox(
                                width: 30,
                              ),
                              Visibility(
                                visible: activeOrdersList[index].stopTime==''||activeOrdersList[index].stopTime=='null',
                                child: Column(
                                  children: [
                                    IconButton(
                                      iconSize: 30,
                                      icon:  Icon(
                                        Icons.download,
                                        color:activeOrdersList[index].tankerRunningStatus=='1'?Colors.red: Colors.green,
                                      ),
                                      onPressed: () async{

                                        if(activeOrdersList[index].tankerRunningStatus!='0'){
                                          var payload = new Map<String, dynamic>();
                                          payload["action"] = 'stop';
                                          payload["percentage"] = '';

                                          var capacity = await AppSettings.startAndStop(activeOrdersList[index].bookingid,payload);

                                          print(capacity);
                                          //var modelTanksViewList = jsonDecode(capacity)['data'];
                                          setState(() {
                                            activeOrdersList[index].tankerRunningStatus='0';
                                            activeOrdersList[index].stopTime=jsonDecode(capacity)['stop time'];
                                          });
                                        }
                                        else{
                                          var payload = new Map<String, dynamic>();
                                          payload["action"] = 'start';
                                          payload["percentage"] = '';

                                          var capacity = await AppSettings.startAndStop(activeOrdersList[index].bookingid,payload);

                                          print(capacity);
                                          //var modelTanksViewList = jsonDecode(capacity)['data'];

                                          setState(() {
                                            activeOrdersList[index].tankerRunningStatus='1';
                                            activeOrdersList[index].startTime=jsonDecode(capacity)['start time'];
                                          });
                                        }

                                      },
                                    ),
                                    Text(
                                      'Download Water',
                                      style: iconBelowTextStyle(),
                                    ),
                                  ],
                                ),
                              ),
                              SizedBox(width: 10,),



                            ],
                          ),
                          SizedBox(height: 5,),
                          Row(children: [
                            Column(

                              children: [

                                Visibility(
                                    visible:activeOrdersList[index].startTime!=''&&activeOrdersList[index].startTime!='null',
                                    child:Row(
                                      children: [
                                        Text('Start Time:',style: labelTextStyle(),),
                                        SizedBox(width: 5,),
                                        Text(activeOrdersList[index].startTime,style: valuesTextStyle(),)
                                      ],
                                    )),
                                SizedBox(height: 5,),
                                Visibility(
                                    visible:activeOrdersList[index].stopTime!=''&&activeOrdersList[index].stopTime!='null',
                                    child:Row(
                                      children: [
                                        Text('Stop Time:',style: labelTextStyle(),),
                                        SizedBox(width: 5,),
                                        Text(activeOrdersList[index].stopTime,style: valuesTextStyle(),)
                                      ],
                                    ))
                              ],
                            ),
                            SizedBox(width: 10,),
                            Visibility(
                              visible:activeOrdersList[index].stopTime!=''&&activeOrdersList[index].stopTime!='null',
                              child: ElevatedButton(
                                style: ElevatedButton.styleFrom(
                                  primary: primaryColor, // background
                                  onPrimary: Colors.white, // foreground
                                ),
                                onPressed: () {

                                  showFinishOrderDialog(activeOrdersList[index]);

                                },
                                child: const Text('Finish')),)

                          ],)

                        ],
                      ),
                    ),
                  ],
                ),
              ),
            );
          });
    }
    else {
      return Center(
          child: Padding(
            padding: EdgeInsets.fromLTRB(0, 40, 0, 0),
            child: isSereverIssueConnected
                ? Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Image(
                  image: AssetImage('images/serverissue.png'),
                  //  height: MediaQuery.of(context).size.height * .10,
                ),
                SizedBox(
                  height: 20,
                ),
                Text(
                  'There is an issue at server please try after some time',style:serverIssueTextStyle() ,),
              ],
            )
                :  Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Image(
                  image: AssetImage('images/no_data.png'),
                  //  height: MediaQuery.of(context).size.height * .10,
                ),
                SizedBox(
                  height: 20,
                ),
                Text(
                  'No Connected Tankers',style:serverIssueTextStyle() ,),
              ],
            ),
          ));
    }
  }

  modelBottomSheet(var obj){
    showModalBottomSheet<void>(
      context: context,
      builder: (BuildContext context) {
        return SizedBox(
        height: MediaQuery.of(context).size.height * .300,
          child: Padding(
            padding: EdgeInsets.all(10),
            child: Row(
              children: <Widget>[

                Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text('Tanker Name :', style: labelTextStyle()),
                    Text('Capacity Of Tanker :', style: labelTextStyle()),
                    Text('Booking Id :', style: labelTextStyle()),
                    Text('Date Of Order :', style: labelTextStyle()),
                    Text('Type Of Water :', style: labelTextStyle()),
                    Text('Start Time :', style: labelTextStyle()),
                    Text('Stop Time :', style: labelTextStyle()),
                    Text('Initial Water Level :', style: labelTextStyle()),
                    Text('Final Water Level :', style: labelTextStyle()),
                    Text('Delivered Water :', style: labelTextStyle()),
                    Text('Actual Price :', style: labelTextStyle()),
                    Text('Amount Paid :', style: labelTextStyle()),
                    Text('Amount Due :', style: labelTextStyle()),
                    Text('Payment Mode :', style: labelTextStyle()),
                  ],
                ),
                Expanded(
                  child:Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(obj.tankerName,
                          style: valuesTextStyle()),
                      Text(obj.capacity+' Ltrs',
                          style: valuesTextStyle()),
                      Text(obj.bookingid,
                          style:TextStyle(fontSize: 12,fontWeight: FontWeight.bold,overflow: TextOverflow.ellipsis,)),
                      Text(obj.dateOfOrder,
                          style:TextStyle(fontSize: 12,fontWeight: FontWeight.bold,overflow: TextOverflow.ellipsis,)),
                      Text(obj.typeofwater,
                          style:TextStyle(fontSize: 12,fontWeight: FontWeight.bold,overflow: TextOverflow.ellipsis,)),
                      Text(obj.startTime,
                          style:TextStyle(fontSize: 12,fontWeight: FontWeight.bold,overflow: TextOverflow.ellipsis,)),
                      Text(obj.stopTime,
                          style:TextStyle(fontSize: 12,fontWeight: FontWeight.bold,overflow: TextOverflow.ellipsis,)),
                      Text(obj.initialWaterLevel+' Ltrs',
                          style:TextStyle(fontSize: 12,fontWeight: FontWeight.bold,overflow: TextOverflow.ellipsis,)),
                      Text(obj.finalWaterLevel+' Ltrs',
                          style:TextStyle(fontSize: 12,fontWeight: FontWeight.bold,overflow: TextOverflow.ellipsis,)),
                      Text(obj.deliverdWater+' Ltrs',
                          style:TextStyle(fontSize: 12,fontWeight: FontWeight.bold,overflow: TextOverflow.ellipsis,)),
                      Text(obj.price,
                          style:TextStyle(fontSize: 12,fontWeight: FontWeight.bold,overflow: TextOverflow.ellipsis,)),
                      Text(obj.amountPaid,
                          style:TextStyle(fontSize: 12,fontWeight: FontWeight.bold,overflow: TextOverflow.ellipsis,)),
                      Text(obj.amountDue,
                          style:TextStyle(fontSize: 12,fontWeight: FontWeight.bold,overflow: TextOverflow.ellipsis,)),
                      Text(obj.paymentMode,
                          style:TextStyle(fontSize: 12,fontWeight: FontWeight.bold,overflow: TextOverflow.ellipsis,)),



                    ],
                  ),
                ),

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

  Widget completedOrders(){
    if (completedOrdersList.length != 0) {
      return ListView.builder(
          padding: EdgeInsets.all(8),
          itemCount: completedOrdersList.length,
          itemBuilder: (BuildContext context, int index) {
            return Card(
              child: Padding(
                padding: EdgeInsets.all(8),
                child: Container(
                    child:Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Column(
                          mainAxisAlignment: MainAxisAlignment.start,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text('Tanker Name :', style: labelTextStyle()),
                            Text('Booking Id :', style: labelTextStyle()),
                            Text('Date Of Order :', style: labelTextStyle()),
                          ],
                        ),
                        Expanded(
                          child:Column(
                            mainAxisAlignment: MainAxisAlignment.start,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(completedOrdersList[index].tankerName,
                                  style: valuesTextStyle()),
                              Text(completedOrdersList[index].bookingid,
                                  style:TextStyle(fontSize: 12,fontWeight: FontWeight.bold,overflow: TextOverflow.ellipsis,)),
                              Text(completedOrdersList[index].dateOfOrder,
                                  style:TextStyle(fontSize: 12,fontWeight: FontWeight.bold,overflow: TextOverflow.ellipsis,)),

                            ],
                          ),
                        ),
                        Expanded(
                          child: TextButton(
                            onPressed: () {
                              modelBottomSheet(completedOrdersList[index]);
                            },
                            child: const Text(
                              'More Details',
                              style: TextStyle(
                                color: primaryColor,
                                fontSize: 15,
                                decoration: TextDecoration.underline,

                              ),
                            ),
                          ),
                        )
                      ],
                    )

                )
              ),
            );
          });
    }
    else {
      return Center(
          child: Padding(
            padding: EdgeInsets.fromLTRB(0, 40, 0, 0),
            child: isSereverIssueConnected
                ? Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Image(
                  image: AssetImage('images/serverissue.png'),
                  //  height: MediaQuery.of(context).size.height * .10,
                ),
                SizedBox(
                  height: 20,
                ),
                Text(
                  'There is an issue at server please try after some time',style:serverIssueTextStyle() ,),
              ],
            )
                :  Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Image(
                  image: AssetImage('images/no_data.png'),
                  //  height: MediaQuery.of(context).size.height * .10,
                ),
                SizedBox(
                  height: 20,
                ),
                Text(
                  'No Connected Tankers',style:serverIssueTextStyle() ,),
              ],
            ),
          ));
    }
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Booking Data'),
        backgroundColor: primaryColor,
        bottom: TabBar(
          controller: _controller,
          tabs: topTabs,
          indicatorColor: Colors.blue,
          unselectedLabelColor: Colors.white60,
          indicatorWeight: 2,
        ),),
      /* body: */
      body: TabBarView(controller: _controller, children: [
        Container(
          //color: Colors.lightBlueAccent,
          child: isLoading?Center(
            child: CircularProgressIndicator(
              color: primaryColor,
              strokeWidth: 5.0,
            ),
          ):activeOrders(),
        ),
        Container(
          //color: Colors.lightBlueAccent,
          child: isLoading?Center(
            child: CircularProgressIndicator(
              color: primaryColor,
              strokeWidth: 5.0,
            ),
          ):completedOrders(),
        ),
      ]),
    );
  }
}
