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/companyoffrers.dart';
import 'package:healthcare_pharmacy/getmedicines.dart';
import 'package:healthcare_pharmacy/maps/app_colors.dart';
import 'package:healthcare_pharmacy/medicinecart.dart';
import 'package:healthcare_pharmacy/models/addoffer_model.dart';
import 'package:healthcare_pharmacy/models/biddingrequest_model.dart';
import 'package:healthcare_pharmacy/models/companyoffer_model.dart';
import 'package:healthcare_pharmacy/settings.dart';

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

class GetAllOffers extends StatefulWidget {
  var bookidID;

  GetAllOffers({
    this.bookidID
  });
  @override
  State<GetAllOffers> createState() => _GetAllOffersState();
}

class _GetAllOffersState extends State<GetAllOffers> {
  String Url = '';
  List<GetOffersDetailsModel> offersList = [];
  List<GetOffersDetailsModel> prescriptionsListOriginal = [];
  bool isPrescriptionsDataLoading = false;
  bool isSereverIssue = false;
  bool isLoading=false;
  List<String> checked = [];
  TextEditingController BookingidController = TextEditingController();
  TextEditingController offerCodeController = TextEditingController();




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


    try {
      var data = await AppSettings.getOffers();
      setState(() {
        List<dynamic> responseData = jsonDecode(data)['data'];
        offersList  = responseData
            .map((jsonObject) => GetOffersDetailsModel.fromJson(jsonObject))
            .toList();
        isLoading = false;
      });

    } catch (error) {
      setState(() {
        isLoading = false;
        isSereverIssue = true;
      });
    }
  }

  @override
  void initState() {
    getActiveOffersViewData();
    super.initState();
    BookingidController.text=widget.bookidID;
  }

  void _onCheckboxChanged(String id, bool value) {
    setState(() {
      if (value) {
        checked.add(id);
      } else {
        checked.remove(id);
      }
    });
  }

  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 _allPharmacies() {
    if (offersList.length != 0) {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.end,
        children: [
          Expanded(
            child: ListView.builder(
              padding: EdgeInsets.all(0),
              itemCount: offersList.length,
              itemBuilder: (BuildContext context, int index) {
                return Card(
                  child: Padding(
                    padding: EdgeInsets.all(8),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      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,
                              ),
                            ),
                          ),
                          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(
                                offersList[index].offer_name
                                    .toString()
                                    .toUpperCase(),
                                style: valuesTextStyle(),
                              ),
                              Text(
                                offersList[index].offer_code
                                    .toString()
                                    .toUpperCase(),
                                style: valuesTextStyle(),
                              ),
                              Text(
                                offersList[index].category
                                    .toString()
                                    .toUpperCase(),
                                style: valuesTextStyle(),
                              ),
                              Text(
                                offersList[index].description
                                    .toString()
                                    .toUpperCase(),
                                style: valuesTextStyle(),
                              ),
                            ],
                          ),
                        ),
                        Checkbox(
                          value: checked.contains(
                              offersList[index].offer_code.toString()),
                          onChanged: (value) {
                            _onCheckboxChanged(
                                offersList[index].offer_code.toString(),
                                value ?? false);
                          },
                        ),
                      ],
                    ),
                  ),
                );
              },
            ),
          ),

          Container(
            padding: const EdgeInsets.fromLTRB(10, 0, 10, 0),
            child:TextButton(
              onPressed: () {
                // Add your button click logic here
              },
              child: Text(
                'OfferId:$checked',
                style: TextStyle(
                  fontSize: 15,
                  color: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(10, 0, 10, 0),
              child: ElevatedButton(
                style: ElevatedButton.styleFrom(
                  primary: primaryColor, // background
                  onPrimary: Colors.white, // foreground
                ),
                onPressed: ()async {
                  // Get the selected offer code from the checked list
                  String selectedOfferCode = checked.isNotEmpty ? checked[0] : '';

                  // Check if an offer code is selected
                  if (selectedOfferCode.isNotEmpty) {
                    bool discountOfferStatus = await AppSettings.discountOffer(
                      selectedOfferCode,
                      widget.bookidID,
                    );

                    if (discountOfferStatus) {
                      AppSettings.longSuccessToast('Offer added successfully');
                      Navigator.of(context).pop(true);
                      await Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (context) => MedicineCartList())
                      );
                    } else {
                      AppSettings.longFailedToast('Offer addition failed');
                    }
                  } else {
                    // Handle the case where no offer code is selected
                    AppSettings.longFailedToast('Please select an offer');
                  }
                },
                child:  Text('Submit'),
              )),
        ],
      );
    } 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,),
            ],
          ),
        ),
      );
    }
  }



  /**/

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