
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:healthcare_pharmacy/medicinecart.dart';
import 'package:healthcare_pharmacy/settings.dart';
import 'package:quantity_input/quantity_input.dart';
import 'package:flutter/services.dart';
import 'dart:io' show File, Platform;
import 'package:location/location.dart' as locationmap;


class MedicineDetails extends StatefulWidget {
  var name;
  var price;
  var bookid;

  MedicineDetails({
    this.name,this.price,this.bookid
  });

  @override
  State<MedicineDetails> createState() => _deliverboyState();
}

class _deliverboyState extends State<MedicineDetails> {


  TextEditingController MedicineNameController = TextEditingController();
  TextEditingController MedicineQuantityController = TextEditingController();
  TextEditingController MedicinePriceController = TextEditingController();
  TextEditingController BookingidController = TextEditingController();
  String selectedOptionsText = '';
  List medicineCheckboxes = ["BB","AB","BL","AL","BD","AD"];
  String medname = '';
  String medprice = '';
  int initialValue = 0;
  double enteredValue = 0.0;


  @override
  void initState() {
    super.initState();
    MedicineNameController.text=widget.name;
    MedicinePriceController.text=widget.price;
    BookingidController.text=widget.bookid;
  }

  double getTotalAmount() {
    return enteredValue * initialValue;
  }

  void toggleOption(String option) {
    setState(() {
      if (selectedOptionsText.contains(option)) {
        selectedOptionsText = selectedOptionsText
            .replaceAll('$option,', '') // Remove option from the string
            .replaceAll(', $option', '') // Remove option from the string
            .trim(); // Remove leading/trailing spaces
      } else {
        if (selectedOptionsText.isEmpty) {
          selectedOptionsText = option;
        } else {
          selectedOptionsText += ', $option';
        }
      }
    });
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar:AppSettings.appBar('Medicine Details'),
      body: SafeArea(
          child: SingleChildScrollView(
            child: Column(
              children: <Widget>[
                const SizedBox(
                  height: 15,
                ),
                Container(
                    height: MediaQuery.of(context).size.height * .15,
                    width: double.infinity,
                    child: Image(
                      image: const AssetImage('images/logo.png'),
                      height: MediaQuery.of(context).size.height * .25,
                    )),
                const SizedBox(
                  height: 15,
                ),
                Container(
                  //padding: const EdgeInsets.fromLTRB(10, 10, 10, 0),
                  padding: const EdgeInsets.all(10),
                  child: TextFormField(
                    cursorColor: greyColor,
                    controller: MedicineNameController,
                    textCapitalization: TextCapitalization.characters,
                    decoration: const InputDecoration(
                      prefixIcon: Icon(
                        Icons.medical_information,
                        color: greyColor,
                      ),
                      border: OutlineInputBorder(
                          borderSide: BorderSide(color: greyColor)),
                      focusedBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: greyColor),
                      ),
                      enabledBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: greyColor),
                      ),
                      labelText: 'Medicine Name',
                      labelStyle: TextStyle(
                        color: greyColor, //<-- SEE HERE
                      ),
                    ),
                  ), //tanker name
                ),
                const SizedBox(
                  height: 15,
                ),
                ListView.builder(
                  shrinkWrap: true,
                  itemCount: (medicineCheckboxes.length / 2).ceil(), // Assuming 2 columns
                  itemBuilder: (context, index) {
                    final start = index * 2;
                    final end = start + 2 > medicineCheckboxes.length
                        ? medicineCheckboxes.length
                        : start + 2;

                    return Row(
                      children: [
                        for (int i = start; i < end; i++)
                          Expanded(
                            child: CheckboxListTile(
                              value: selectedOptionsText.contains(medicineCheckboxes[i]),
                              onChanged: (value) => toggleOption(medicineCheckboxes[i]),
                              title: Text(medicineCheckboxes[i]),
                              controlAffinity: ListTileControlAffinity.leading,
                              dense: true,
                              contentPadding: EdgeInsets.zero,
                            ),
                          ),
                      ],
                    );
                  },
                ),


                const SizedBox(
                  height: 5,
                ),
                Container(
                  padding: const EdgeInsets.all(10),
                  child: Row(
                    children: [
                      Expanded(
                        child: TextFormField(
                          cursorColor: greyColor,
                          controller: MedicineQuantityController,
                          readOnly: true,
                          textCapitalization: TextCapitalization.characters,
                          decoration: const InputDecoration(
                            prefixIcon: Icon(
                              Icons.production_quantity_limits,
                              color: greyColor,
                            ),
                            border: OutlineInputBorder(
                              borderSide: BorderSide(color: greyColor),
                            ),
                            focusedBorder: OutlineInputBorder(
                              borderSide: BorderSide(color: greyColor),
                            ),
                            enabledBorder: OutlineInputBorder(
                              borderSide: BorderSide(color: greyColor),
                            ),
                            labelText: 'Medicine Quantity',
                            labelStyle: TextStyle(
                              color: greyColor,
                            ),
                          ),
                        ),
                      ),
                      const SizedBox(width: 10), // Adjust the spacing as needed
                      QuantityInput(
                        label: 'Select Medicine Quantity',
                        value: initialValue,
                        iconColor: Colors.white,
                        buttonColor: primaryColor,
                        onChanged: (value) {
                          setState(() {
                            enteredValue = double.tryParse(value) ?? 0.0;
                            initialValue = int.parse(value.replaceAll(',', ''));
                            MedicineQuantityController.text = initialValue.toString();
                            // MedicinePriceController.text = '${getTotalAmount()}';
                          });
                        },
                      ),
                    ],
                  ),
                ), //alternative phone number
                //phone number
                const SizedBox(
                  height: 5,
                ),
                Container(
                  //padding: const EdgeInsets.fromLTRB(10, 10, 10, 0),
                  padding: const EdgeInsets.all(10),
                  child: TextFormField(
                    cursorColor: greyColor,
                    controller: MedicinePriceController,
                    textCapitalization: TextCapitalization.characters,
                    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: 'Medicine Price',
                      labelStyle: TextStyle(
                        color: greyColor, //<-- SEE HERE
                      ),
                    ),
                  ), //tanker name
                ), //alternative phone number

                const SizedBox(
                  height: 5,
                ),

                Container(
                    width: MediaQuery.of(context).size.width * .99,
                    height: 50,
                    padding: const EdgeInsets.fromLTRB(10, 0, 10, 0),
                    child: ElevatedButton(
                      style: ElevatedButton.styleFrom(
                        primary: primaryColor, // background
                        onPrimary: Colors.white, // foreground
                      ),
                      onPressed: () async {
                        if (MedicineNameController.text != '' &&
                            MedicineQuantityController.text != ''&&
                            MedicinePriceController.text != ''
                        ) {
                          AppSettings.preLoaderDialog(context);
                          var response = await AppSettings.addToCart(BookingidController.text,MedicineQuantityController.text,
                              MedicinePriceController.text,MedicineNameController.text,selectedOptionsText);
                          //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(
                                  "Medicine Added to Cart Successfully");
                              /* MedicineNameController.text = '';
                                  MedicineQuantityController.text = '';
                                  MedicinePriceController.text = '';
                                  //BookingidController.text = '';*/
                              await Navigator.push(
                                context,
                                MaterialPageRoute(
                                    builder: (context) => MedicineCartList(bookidID:BookingidController.text.toString())),
                              );


                            }
                            else{
                              Navigator.of(context,rootNavigator: true).pop();
                              AppSettings.longFailedToast("Medicine Not Added to Cart Successfully");
                            }

                            /* try {
                                if (medicineStatus) {
                                  Navigator.of(context,rootNavigator: true).pop();
                              AppSettings.longSuccessToast(
                             "Medicine Added to Cart Successfully");
                                 *//* MedicineNameController.text = '';
                                  MedicineQuantityController.text = '';
                                  MedicinePriceController.text = '';
                                  //BookingidController.text = '';*//*
                              await Navigator.push(
                                  context,
                          MaterialPageRoute(
                             builder: (context) => MedicineCartList(bookidcart:BookingidController.text.toString())),
                        );

                          //Navigator.of(context).pushNamed('/tanksview');
                      } else {
                                  Navigator.of(context,rootNavigator: true).pop();
                       AppSettings.longFailedToast("Medicine Not Added to Cart Successfully");
                 }*/
                          } catch (exception) {
                            print(exception);
                          }
                        }
                        else {
                          AppSettings.longFailedToast("Please enter valid details");
                        }
                      },

                      child: const Text(
                        'NEXT',
                        style: TextStyle(
                          fontSize: 25,
                        ),
                      ),
                    )),

              ],
            ),
          )),
    );
  }
}
