import 'package:flutter/material.dart';
import 'package:supplier_new/common/settings.dart';

class EditOrderRequests extends StatefulWidget {
  var order;
  String? advance;
  var status;
  EditOrderRequests({this.order,this.advance,this.status});

  @override
  State<EditOrderRequests> createState() => _EditOrderRequestsState();
}

class _EditOrderRequestsState extends State<EditOrderRequests> {
  final TextEditingController tankerPriceController = TextEditingController();
  final TextEditingController waterTypeController = TextEditingController();
  final TextEditingController capacityController = TextEditingController();
  final TextEditingController timeController = TextEditingController();
  final TextEditingController quantityController = TextEditingController();
  final TextEditingController advanceController = TextEditingController();
  final TextEditingController dateController = TextEditingController();

  @override
  void initState() {
    super.initState();
    tankerPriceController.text='${widget.order.quoted_amount}';
    waterTypeController.text='${widget.order.type_of_water}';
    quantityController.text='${widget.order.quantity}';
    capacityController.text='${widget.order.capacity}';
    timeController.text='${widget.order.averageTime}';
    dateController.text='${widget.order.date}';
    advanceController.text='${widget.advance}';
    // Update summary in real-time as user types
    tankerPriceController.addListener(() => setState(() {}));
    /*capacityController.addListener(() => setState(() {}));
    quantityController.addListener(() => setState(() {}));
    dateController.addListener(() => setState(() {}));
    timeController.addListener(() => setState(() {}));
    waterTypeController.addListener(() => setState(() {}));*/
    advanceController.addListener(() => setState(() {}));
  }

  @override
  Widget build(BuildContext context) {
    int tankerPrice = int.tryParse(tankerPriceController.text) ?? 0;
    int updatedQuantity=int.tryParse(quantityController.text) ?? 0;
    String updatedCapacity=capacityController.text ?? '';
    // Parse booking/advance as a double to accept "150.0" then convert to int (round)
    double bookingChargesDouble = double.tryParse(advanceController.text.trim()) ?? 0.0;
    int bookingCharges = bookingChargesDouble.round(); // or .toInt() / .floor() as you prefer

    int totalPrice = (tankerPrice * updatedQuantity) + bookingCharges;
    int advancePayable = bookingCharges; //
    int amountToPayAfterDelivery=totalPrice-bookingCharges;

    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        backgroundColor:  Colors.white,
        elevation: 0,
        scrolledUnderElevation: 0,
        title: Text(
          'Edit Order',
          style: fontTextStyle(16, Color(0XFF2A2A2A), FontWeight.w600),
        ),
        leading: GestureDetector(
          onTap: () {
            Navigator.pop(context);
          },
          child: Padding(
            padding:
            const EdgeInsets.fromLTRB(16, 8, 8, 8), // Add padding if needed
            child: Image.asset(
              'images/cross.png', // Replace with your image path
              fit: BoxFit.contain,
              color: Color(0XFF2A2A2A),
              height: 24,
              width: 24,

            ),
          ),
        ),
        iconTheme: IconThemeData(color: Color(0XFF2A2A2A)),
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 🔹 Club Info Card
            Material(
              elevation: 4, // shadow depth
              borderRadius: BorderRadius.circular(12),
              child: Container(
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(12),
                  color: Colors.white, // Material needs a background color
                  border: Border.all(color: Color(0XFFC9C2F0),width: 0.5),
                ),
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children:  [
                        Container(
                          padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                          decoration: BoxDecoration(
                            color: Color(0XFFFFFFFF),
                            borderRadius: BorderRadius.circular(4),
                            border: Border.all(
                              color: widget.status.statusColor,
                              width: 0.5,
                            ),
                          ),
                          child: Text(
                              widget.status.status,
                              style: fontTextStyle(12, widget.status.statusColor, FontWeight.w500)
                          ),
                        ),
                        SizedBox(height: 4),
                        Text(
                          widget.order.building_name,
                          style: fontTextStyle(20, const Color(0XFF2D2E30), FontWeight.w600),
                        ),
                        Text(
                          widget.order.displayAddress,
                          style: fontTextStyle(12, const Color(0XFF939495), FontWeight.w400),
                        ),
                      ],
                    ),
                    const Spacer(),
                    Text(
                      widget.order.distanceInKm.toString()+'Km',
                      style: fontTextStyle(12, const Color(0XFF939495), FontWeight.w400),
                    ),
                  ],
                ),
              ),
            ),

            SizedBox(height:MediaQuery.of(context).size.height * .06,),
            Text("ORDER DETAILS",
                style: fontTextStyle(12, const Color(0XFF2D2E30), FontWeight.w600),),
            const SizedBox(height: 12),
            // 🔹 Two in a row
            _twoFields(tankerPriceController, "Tanker Price",'images/price.png',false, null, null,null,null),
            _twoFields(capacityController, "Capacity",'images/capacity.png',true,quantityController, "Quantity",'images/quantity.png',true),
            _twoFields(waterTypeController, "Water Type",'images/water.png',true,advanceController, "Booking Charges",'images/advance.png',false),
            _twoFields(dateController, "Date",'images/calendar_appbar.png',true,timeController, "Time Of Delivery",'images/time.png',true),

            const SizedBox(height: 20),
            Text("UPDATED PAYMENT SUMMARY",
                style: fontTextStyle(12,Color(0XFF2D2E30),FontWeight.w600),),
            const SizedBox(height: 12),
            _summaryRow("Tanker Price", "₹ $tankerPrice"),
            _summaryRow("Quantity", " $updatedQuantity"),
            _summaryRow("Capacity", "$updatedCapacity"),
            _summaryRow("Booking Charges", "₹ $bookingCharges"),
            _summaryRow("Total Price", "₹ $totalPrice"),
            const Divider(),

            _summaryRow("Booking Charges Payable", "₹ $advancePayable"),
            _summaryRow("Amount to Pay (After Delivery)", "₹ $amountToPayAfterDelivery"),
          ],
        ),
      ),
      bottomNavigationBar: Container(
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
        decoration: BoxDecoration(
          color: Color(0XFFFFFFFF),
          border: Border(top: BorderSide(color: Color(0XFFF5F6F6))),
        ),
        child: Row(
          children: [
            Expanded(
              child: OutlinedButton(
                style: OutlinedButton.styleFrom(
                  foregroundColor: Color(0XFF000000),
                  backgroundColor: Color(0xFFFFFFFF),
                  side: BorderSide(color: Color(0xFF939495)),
                  padding: EdgeInsets.symmetric(vertical: 10),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(24), // <-- radius here
                  ),
                ),
                onPressed: () {
                  Navigator.pop(context);
                },
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [

                    Text(
                      "Cancel",
                      style: fontTextStyle(14, const Color(0XFF000000), FontWeight.w400),
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(width: 8),
            Expanded(
              child: OutlinedButton(
                style: OutlinedButton.styleFrom(
                  foregroundColor: Color(0XFFFFFFFF),
                  backgroundColor: Color(0xFF8270DB),
                  side: BorderSide(color: Color(0xFF8270DB)),
                  padding: EdgeInsets.symmetric(vertical: 10),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(24), // <-- radius here
                  ),
                ),
                onPressed: () async{
                  AppSettings.preLoaderDialog(context);

                  bool isOnline = await AppSettings.internetConnectivity();

                  if (isOnline) {
                    var payload = new Map<String, dynamic>();
                    payload["supplierId"] = AppSettings.supplierId;
                    payload["amount"] = int.parse(tankerPriceController.text);
                    payload["delivery_charges"] = widget.advance;
                    payload["action"] = 'accept';

                    bool status = await AppSettings.acceptOrderRequests(
                        payload, widget.order.dbId);

                    try {
                      if (status) {
                        Navigator.of(context,rootNavigator: true).pop();
                        Navigator.pop(context, true);
                        Navigator.pop(context, true);
                      }
                      else{
                        Navigator.of(context,rootNavigator: true).pop();
                        AppSettings.longFailedToast("Accept of order request Failed");
                      }
                    } catch (e) {
                      Navigator.of(context,rootNavigator: true).pop();
                      print(e);
                    }
                  }
                  else{
                    Navigator.of(context,rootNavigator: true).pop();
                    AppSettings.longFailedToast("Please Check internet");
                  }
                },
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [

                    Text(
                      "Send",
                      style: fontTextStyle(14, const Color(0XFFFFFFFF), FontWeight.w400),
                    ),
                    SizedBox(width: 12),
                    Image.asset('images/send.png', height: 20, width: 20),

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

  /// 🔹 Two fields side by side
  Widget _twoFields(TextEditingController? controller1, String? label1,String? path1, bool? readOnly1,
      TextEditingController? controller2, String? label2,String? path2,bool? readOnly2) {
    return Row(
      children: [
        Expanded(
          child: _textField(controller1, label1,path1,readOnly1!),
        ),
        const SizedBox(width: 10),
        if (controller2 != null)
          Expanded(
            child: _textField(controller2, label2,path2,readOnly2!),
          ),
      ],
    );
  }

  /// 🔹 Custom text field
  Widget _textField(TextEditingController? controller, String? label,String? path,bool readOnly) {
    return Container(
      margin: const EdgeInsets.only(bottom: 12),
      child: TextField(
        controller: controller,
        cursorColor: primaryColor,
        readOnly: readOnly,
        decoration: InputDecoration(
          counterText: '',
          filled: false,
          fillColor: Colors.white,
          prefixIcon: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 6.0, vertical: 6.0),
            child: SizedBox(
              width: 18,
              height: 18,
              child: Image.asset(
                path!,
                fit: BoxFit.contain,
                color: Color(0XFFC3C4C4),
              ),
            ),
          ),
          prefixIconConstraints: BoxConstraints(
            minWidth: 24,
            minHeight: 24,
          ),
          border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(4.0),
              borderSide: BorderSide(color: Color(0XFFC3C4C4),
                width: 1,)),
          focusedBorder: !readOnly?OutlineInputBorder(
            borderRadius: BorderRadius.circular(4.0),
            borderSide: BorderSide(color: Color(0XFF8270DB),width: 1,),
          ):OutlineInputBorder(
            borderRadius: BorderRadius.circular(4.0),
            borderSide: BorderSide(color: Color(0XFFC3C4C4),width: 1,),
          ),

          enabledBorder: OutlineInputBorder(
            borderRadius: BorderRadius.circular(4.0),
            borderSide: BorderSide(color: Color(0XFFC3C4C4)),
          ),
          labelText: label,
          labelStyle:fontTextStyle(12,Color(0XFF646566),FontWeight.w400),
          /*  TextStyle(color: greyColor, fontWeight: FontWeight.bold //<-- SEE HERE
    ),*/
        ),
        style:fontTextStyle(12,Color(0XFF343637),FontWeight.w500),
      ),
    );
  }

  /// 🔹 Summary row
  Widget _summaryRow(String title, String value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 6),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(title, style: fontTextStyle(12,Color(0XFF646566),FontWeight.w400),),
          Text(value,
              style: fontTextStyle(12,Color(0XFF2D2E30),FontWeight.w500),),
        ],
      ),
    );
  }

}
