import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:geolocator/geolocator.dart';
import 'package:healthcare_pharmacy/getmedicines.dart';
import 'package:healthcare_pharmacy/models/biddingrequest_model.dart';
import 'package:healthcare_pharmacy/settings.dart';

import 'package:image_picker/image_picker.dart';
import 'package:photo_view/photo_view.dart';

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

  @override
  State<BiddingRequests> createState() => _BiddingRequestsState();
}

class _BiddingRequestsState extends State<BiddingRequests> {
  String Url = '';
  List<BiddingRequestsModel> prescriptionsList = [];
  bool isPrescriptionsDataLoading = false;
  bool isSereverIssue = false;
  bool isLoading=false;
  Future<void> getAllPrescriptions() async {
    isPrescriptionsDataLoading=true;
    try {
      var response = await AppSettings.getAllBiddingRecords();

        /*for (var item in data) {
          BiddingRequestsModel biddingRequestsModel=new BiddingRequestsModel();
          biddingRequestsModel.bidding_bookingid = item['bookingId']!;
          biddingRequestsModel.pharmacyid_bidding = item['pharmacyId']!;
          biddingRequestsModel.custumerid_bidding = item['customerId']!;
          biddingRequestsModel.amount_bidding = item['biddingAmount']!.toString();

          String? firstName = item['customerDetails']?['firstName'];
          String? contactNumber = item['customerDetails']?['profile']?['contactNumber'];

          print('First Name: $firstName');

          biddingRequestsModel.bidding_firstName = firstName ; // Provide a default value if firstName is null

          // biddingRequestsModel.bidding_contactNumber=contactNumber;
          prescriptionsList.add(biddingRequestsModel);
        }*/

        setState(() {
          prescriptionsList =
              ((jsonDecode(response)['data']) as List).map((dynamic model) {
                return BiddingRequestsModel.fromJson(model);
              }).toList();
          isPrescriptionsDataLoading = false;
        });

    } catch (e) {
      setState(() {
        isLoading = false;
        isPrescriptionsDataLoading = false;
      });
    }
  }





  @override
  void initState() {
    getAllPrescriptions();
    //getAllPharmaciesData(dropdownArea);
    super.initState();
  }

  showPicDialog(var imageUrl){
    return showDialog(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return StatefulBuilder(
            builder: (BuildContext context, StateSetter setState) {
              return AlertDialog(
                title: const Text(''),
                content: SingleChildScrollView(
                  child: ListBody(
                    children: <Widget>[
                      Container(
                          width: MediaQuery.of(context).size.width * .10,
                          height: MediaQuery.of(context).size.height * .50,
                          child: PhotoView(
                            imageProvider: NetworkImage(imageUrl) as ImageProvider,
                            maxScale: PhotoViewComputedScale.contained * 4.0,
                            minScale: PhotoViewComputedScale.contained,
                            initialScale: PhotoViewComputedScale.contained,
                            basePosition: Alignment.center,

                          )
                      )
                    ],
                  ),
                ),
                actions: <Widget>[
                  TextButton(
                    child: Text('Close', style: textButtonStyle()),
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                  ),
                ],
              );
            });
      },
    );
  }


  Widget _allPrescriptions(){
    if (prescriptionsList.length != 0) {
      return  Column(
          crossAxisAlignment: CrossAxisAlignment.end,
          children: [
            Expanded(child:ListView.builder(
                padding:  EdgeInsets.all(0),
                itemCount: prescriptionsList.length,
                itemBuilder: (BuildContext context, int index) {
                  return GestureDetector(
                    onTap: (){
                      Navigator.push(
                          context,
                          new MaterialPageRoute(
                              builder: (__) => new GetMedicines(medicinebookingid:prescriptionsList[index].bidding_bookingid)));
                    },
                    child: Card(

                      //color: prescriptionsList[index].cardColor,
                      child: Padding(
                        padding:EdgeInsets.all(8) ,
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                GestureDetector(
                                  child: Container(
                                    width: MediaQuery.of(context).size.width * .18,
                                    height:
                                    MediaQuery.of(context).size.height * .10,
                                    decoration: BoxDecoration(
                                        shape: BoxShape.circle,
                                        image: DecorationImage(
                                            image: (AppSettings.updatedImage != null) ? FileImage(AppSettings.updatedImage!) as ImageProvider : AssetImage("images/mobilebg.png"), // picked file
                                            fit: BoxFit.cover)),
                                    /*  decoration: BoxDecoration(
                                      shape: BoxShape.rectangle,
                                      image: DecorationImage(
                                          image: NetworkImage(prescriptionsList[index].prescription_url) as ImageProvider, // picked file
                                          fit: BoxFit.contain)),*/
                                  ),
                                  onTap: (){
                                    // showPicDialog(prescriptionsList[index].prescription_url);

                                  },
                                ),
                                SizedBox(width:MediaQuery.of(context).size.width * .02,),
                                Container(
                                  width: MediaQuery.of(context).size.width * .55,
                                  child: Column(
                                    mainAxisAlignment: MainAxisAlignment.start,
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      Text(prescriptionsList[index].bidding_firstName.toString().toUpperCase(),style: valuesTextStyle()),
                                      Text(prescriptionsList[index].bidding_contactNumber.toString().toUpperCase(),style: valuesTextStyle()),
                                      Text(prescriptionsList[index].bidding_bookingid.toString().toUpperCase(),style: valuesTextStyle()),
                                      Text(prescriptionsList[index].bidding_address.toString().toUpperCase(),style: valuesTextStyle()),
                                      Text(prescriptionsList[index].custumerid_bidding.toString().toUpperCase(),style: valuesTextStyle()),
                                      Text(prescriptionsList[index].pharmacyid_bidding.toString().toUpperCase(),style: valuesTextStyle()),
                                    ],
                                  ),


                                ),

                                Visibility(
                                  visible:true ,

                                    child: prescriptionsList[index].status.toString().toLowerCase()=='pending'?Column(
                                      children: [
                                        TextButton(
                                          child: Text(
                                            'Accept',
                                            style: TextStyle(
                                                fontSize: 15,
                                                color:
                                                primaryColor /*FilteredList[index].text_color*/),
                                          ),
                                          onPressed: () async {
                                            var payload = new Map<String, dynamic>();
                                            payload["pharmacyId"] =AppSettings.healthpharmaIdsign.toString();
                                            payload["action"] = "accept";
                                            bool requestStatus =
                                            await AppSettings.getRequestBiddingDetails(
                                                prescriptionsList[index].bidding_bookingid,
                                                payload);

                                            if (requestStatus) {
                                             // Navigator.of(context).pop();
                                              AppSettings.longSuccessToast(
                                                  "Booking Accepted");
                                              await getAllPrescriptions();

                                            } else {}

                                          },
                                        ),
                                        TextButton(
                                          child: Text(
                                            'Reject',
                                            style: TextStyle(
                                                fontSize: 15,
                                                color:
                                                primaryColor /*FilteredList[index].text_color*/),
                                          ),
                                          onPressed: () async {
                                            var payload = new Map<String, dynamic>();
                                            payload["pharmacyId"] =AppSettings.healthpharmaIdsign.toString();
                                            payload["action"] = "reject";
                                            bool requestStatus =
                                            await AppSettings.getRequestBiddingDetails(
                                                prescriptionsList[index].bidding_bookingid,
                                                payload);

                                            if (requestStatus) {
                                             // Navigator.of(context).pop();
                                              AppSettings.longSuccessToast(
                                                  "Booking Rejected");
                                              await getAllPrescriptions();

                                            } else {}
                                          },
                                        ),
                                      ],
                                    ):Text(prescriptionsList[index].status)),

                              ],

                            ),
                            /*TextButton(
                            child: const Text(
                              'Order Medicines',
                              style: TextStyle(color: primaryColor),
                            ),
                            onPressed: () {

                              Navigator.push(
                                  context,
                                  new MaterialPageRoute(
                                      builder: (__) => new OrderMedicines(prescriptionDetails:prescriptionsList[index])));
                              //signup screen
                            },
                          )*/
                          ],
                        ),
                      ),
                    ),
                  );
                }) ),





          ]);
    }
    else {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              'No Bidding Requests Available',
              style: TextStyle(fontSize: 18),
            ),
          ],
        ),
      );
    }
  }

  /**/

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppSettings.appBar('BiddingRequests'),
      body: isPrescriptionsDataLoading?Center(
        child: CircularProgressIndicator(
          color: primaryColor,
          strokeWidth: 5.0,
        ),
      ): _allPrescriptions(),
    );
  }
}
