import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:healthcare_pharmacy/biddingrequests.dart';
import 'package:healthcare_pharmacy/dashboard.dart';
import 'package:healthcare_pharmacy/getalloffers.dart';
import 'package:healthcare_pharmacy/getmedicines.dart';
import 'package:healthcare_pharmacy/maps/app_colors.dart';
import 'package:healthcare_pharmacy/medicinedetailspage.dart';
import 'package:healthcare_pharmacy/models/biddingrequest_model.dart';
import 'package:healthcare_pharmacy/models/cartview_model.dart';
import 'package:healthcare_pharmacy/models/offersview_model.dart';
import 'package:healthcare_pharmacy/settings.dart';
import 'package:intl/intl.dart';
import 'package:flutter_cupertino_datetime_picker/flutter_cupertino_datetime_picker.dart';


class MedicineCartList extends StatefulWidget {
  var bookidID;

  MedicineCartList({
    this.bookidID
  });

  @override
  State<MedicineCartList> createState() => _MedicineCartListState();
}

class _MedicineCartListState extends State<MedicineCartList> with TickerProviderStateMixin {
  bool isSupplierDataLoading=false;
  bool isSereverIssue = false;
  bool isSereverIssueConnected = false;
  bool isSereverIssuePending = false;
  var startdate;
  var enddate;
   String totalPrice='';
   String medicinetime='';

  String bookingidstring='';
  bool isLoading=false;




  List<BiddingCartviewModel> offersviewList = [];
  TextEditingController medicine_nameController = TextEditingController();
  TextEditingController medicine_quantityController = TextEditingController();
  TextEditingController medicine_priceController = TextEditingController();
  TextEditingController medicine_gstPriceController = TextEditingController();
  TextEditingController medicine_additionalPriceController = TextEditingController();
  TextEditingController medicine_finalPriceController = TextEditingController();
  TextEditingController BookingidController = TextEditingController();
  TextEditingController medicine_timingsController = TextEditingController();


  Future<void> getCartViewData() async {
    isLoading = true;

    try {
      var response = await AppSettings.getCartDetails(widget.bookidID).then((value){
        setState(() {
          // offersviewList = BiddingCartviewModel.fromJson(response['items']) as List<BiddingCartviewModel>;
          offersviewList =
              ((jsonDecode(value)['items']) as List).map((dynamic model) {
                return BiddingCartviewModel.fromJson(model);
              }).toList();

          totalPrice=jsonDecode(value)['totalPrice'].toString();

          print(medicinetime);
          print(totalPrice);
          isLoading = false;
        });
      });
      print("offersviewListdata${jsonDecode(response)}");

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



  @override
  void initState() {
    // TODO: implement initState
    BookingidController.text=widget.bookidID;
    getCartViewData();
    super.initState();
  }

  Widget renderzUi() {
    if (offersviewList.length != 0) {
      return Column(crossAxisAlignment: CrossAxisAlignment.end, children: [
        Expanded(
            child: ListView.builder(
                padding: EdgeInsets.all(0),
                itemCount: offersviewList.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('MedicineName:',
                                            style: labelTextStyle()),
                                        SizedBox(
                                          height: 10,
                                        ),
                                        Text(
                                          'Medicine Timings:',
                                            style: labelTextStyle()),
                                        SizedBox(
                                          height: 10,
                                        ),
                                        Text('MedicineQuantity:',
                                            style: labelTextStyle()),
                                        SizedBox(
                                          height: 10,
                                        ),
                                        Text('MedicinePrice:',
                                            style: labelTextStyle()),
                                      ],
                                    ),
                                    SizedBox(
                                      width: 10,
                                    ),
                                    Column(
                                      mainAxisAlignment:
                                      MainAxisAlignment.spaceBetween,
                                      crossAxisAlignment:
                                      CrossAxisAlignment.start,
                                      children: [
                                        SizedBox(
                                          height: 12,
                                        ),
                                        Text(
                                            offersviewList[index].medicinename_bidding!
                                                .toUpperCase(),
                                            style: valuesTextStyle()),
                                        SizedBox(
                                          height: 12,
                                        ),
                                        Text(
                                            offersviewList[index].medicine_timings![0].medicineTimings!.toUpperCase(),
                                            style: valuesTextStyle()),
                                        SizedBox(
                                          height: 10,
                                        ),
                                        Text(
                                            offersviewList[index].quantity_bidding.toString()
                                                .toUpperCase(),
                                            style: valuesTextStyle()),
                                        SizedBox(
                                          height: 10,
                                        ),
                                        Text(
                                            offersviewList[index].price_bidding.toString()
                                                .toUpperCase(),
                                            style: valuesTextStyle()),
                                        SizedBox(
                                          height: 10,
                                        ),
                                      ],
                                    ),
                                  ],
                                )),
                          ),

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

        Container(
          width: MediaQuery.of(context).size.width,
          height: 50,
          child:TextButton(
            onPressed: () {
              // Add your button click logic here
            },
            child: Text(
              'Total Price:$totalPrice',
              style: TextStyle(
                fontSize: 20,
                color: AppColors.primaryColor, // Text color
                decoration: TextDecoration.underline, // Underline the text
                fontWeight: FontWeight.bold, // Bold text
              ),
            ),
          ),),
       /* Container(
          width: MediaQuery.of(context).size.width,
          height: 30,
          child: Align(
            alignment: Alignment.center,
            child: TextButton(
              onPressed: () async {
                await Navigator.push(
                  context,
                  MaterialPageRoute(
                      builder: (context) => GetAllOffers(bookidID:BookingidController.text.toString())),
                );
              },
              child: Text(
                'Add Offers',
                style: TextStyle(
                  fontSize:15,
                  color: AppColors.primaryColor, // Text color
                  decoration: TextDecoration.underline, // Underline the text
                  fontWeight: FontWeight.bold, // Bold text
                ),
              ),
            ),
          ),
        ),*/

        SizedBox(
          height: 10,
        ),
        Container(
            width: MediaQuery.of(context).size.width,
            height: 60,
            padding: const EdgeInsets.fromLTRB(20, 0, 20, 10),
            child: ElevatedButton(
              style: ElevatedButton.styleFrom(
                primary: primaryColor, // background
                onPrimary: Colors.white, // foreground
              ),
              onPressed: ()  async{
                // Calculate final amount
                double gst = 0.00; // Replace with your actual GST value
                double additionalDiscount = 10.00; // Replace with your actual additional discount value
                double finalAmount = double.parse(totalPrice) + gst - additionalDiscount;

                showDialog(
                  barrierDismissible: false,
                  context: context,
                  builder: (BuildContext context) {
                    // Update controllers with values
                    medicine_priceController.text = totalPrice.toString();
                    medicine_gstPriceController.text = gst.toString();
                    medicine_additionalPriceController.text = additionalDiscount.toString();

                    return AlertDialog(
                      title: Text('Payment Receipt'),
                      content: Column(
                        mainAxisSize: MainAxisSize.min,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text('Total Price: $totalPrice'),
                          Text('GST: $gst'),
                          Text('Additional Discount: $additionalDiscount'),
                          Divider(), // Add a divider line
                          Text('Final Amount: $finalAmount'), // Show final amount
                        ],
                      ),
                      actions: <Widget>[
                        Center(
                          child: ElevatedButton(
                            style: ElevatedButton.styleFrom(
                              primary: primaryColor, // background
                              onPrimary: Colors.white, // foreground
                            ),
                            onPressed: () async {
                              if (medicine_priceController.text != '' &&
                                  medicine_gstPriceController.text != ''&&
                                  medicine_additionalPriceController.text != ''
                              ) {
                                AppSettings.preLoaderDialog(context);
                                var response = await AppSettings.cartFinalAmmount(BookingidController.text,medicine_priceController.text,
                                    medicine_gstPriceController.text,medicine_additionalPriceController.text);
                                print("response$response");

                                //String response= await addToCart("OR1690969760576127","10","300","Dolo650");
                                //print("response$response");
                                try {
                                  if(response.statusCode==200){
                                    var msg=jsonDecode(response.body)['message'];
                                    print(msg);
                                    Navigator.of(context,rootNavigator: true).pop();
                                    AppSettings.longSuccessToast(
                                        "Medicines Final Price Sent Successfully");

                                    await Navigator.push(
                                      context,
                                      MaterialPageRoute(
                                          builder: (context) => Dashboard()),
                                    );


                                  }
                                  else{
                                    Navigator.of(context,rootNavigator: true).pop();
                                    AppSettings.longFailedToast("Failed to Sent Final Medicines Price");
                                  }

                                } catch (exception) {
                                  print(exception);
                                }
                              }
                              else {
                                AppSettings.longFailedToast("Please enter valid details");
                              }

                              Navigator.of(context).pop();
                            },
                            child: Text('Submit'),
                          ),
                        ),
                      ],
                    );
                  },
                );

              },
              child:  Text('CheckOut'),
            )),




      ]);
    } 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: AppBar(
            // Add a back button to the leading property
            backgroundColor: primaryColor,
            leading: IconButton(
              icon: Icon(Icons.arrow_back), // You can use a different back icon if needed
              onPressed: () {
                Navigator.of(context).pop();
                // Implement the navigation logic to go back
               /* Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => GetMedicines()),
                );*/ // This will pop the current route and go back
              },
            ),
            title: Text('Cart Details'),
          ),
          body: isLoading?Center(
            child: CircularProgressIndicator(
              color: primaryColor,
              strokeWidth: 5.0,
            ),
          ):renderzUi(),
        ));
  }
}