import 'dart:convert';

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

class CollectMoney extends StatefulWidget {
  var details;

  CollectMoney({this.details});

  @override
  State<CollectMoney> createState() => _CollectMoneyState();
}

class _CollectMoneyState extends State<CollectMoney> {
  String collectAmountInRupees = '';

  @override
  void initState() {
    super.initState();

    // Safe parsing of amount_due (avoid NaN)
    String raw = widget.details.amount_due?.toString() ?? "";
    double? parsed = double.tryParse(raw);

    if (parsed == null || parsed.isNaN) {
      collectAmountInRupees = "0";
    } else {
      collectAmountInRupees = parsed.toStringAsFixed(0);
    }
  }

  String formatDeliveredDate() {
    final now = DateTime.now();

    // Month names
    const months = [
      "Jan","Feb","Mar","Apr","May","Jun",
      "Jul","Aug","Sep","Oct","Nov","Dec"
    ];

    String day = now.day.toString().padLeft(2, '0');
    String month = months[now.month - 1];
    String year = now.year.toString();

    int hour12 = now.hour > 12 ? now.hour - 12 : (now.hour == 0 ? 12 : now.hour);
    String hour = hour12.toString();
    String minute = now.minute.toString().padLeft(2, '0');
    String ampm = now.hour >= 12 ? "PM" : "AM";

    return "$day-$month-$year $hour:$minute $ampm";
  }

  @override
  Widget build(BuildContext context) {
    // --------------------------------------------
    // 🔥 UPI QR GENERATION
    // --------------------------------------------
    String upiId = widget.details.supplier_upi_id ?? "";
    String supplierName =
    Uri.encodeComponent(widget.details.supplier_name ?? "Supplier");

    String qrData =
        "upi://pay?pa=$upiId&pn=$supplierName&am=$collectAmountInRupees&cu=INR&mam=1";

    // --------------------------------------------

    return
      WillPopScope(
          onWillPop: () async {
            Navigator.pushAndRemoveUntil(
              context,
              MaterialPageRoute(builder: (_) => AllOrders(navigationFrom:"")),
                  (route) => false,
            );
            return false;
          },

          child: Scaffold(
            backgroundColor: Color(0XFFFFFFFF),
            appBar: AppSettings.appBarWithNotificationIcon(
              widget.details.building_name,
              widget.details.type_of_water,
              widget.details.capacity,
              context,
            ),
            body: SafeArea(
              child: SingleChildScrollView(
                physics: const BouncingScrollPhysics(),
                child: Padding(
                  padding: const EdgeInsets.fromLTRB(16, 8, 16, 24),
                  child: Align(
                    alignment: const Alignment(0, -0.25),
                    child: Container(
                      width: double.infinity,
                      constraints: const BoxConstraints(maxWidth: 520),
                      padding: const EdgeInsets.fromLTRB(16, 18, 16, 16),
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(16),
                        border: Border.all(color: const Color(0xFFEDEDED)),
                        boxShadow: const [
                          BoxShadow(
                              color: Colors.black12,
                              blurRadius: 10,
                              offset: Offset(0, 4)),
                        ],
                      ),
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          const SizedBox(height: 4),
                          Text(
                            'Collect money',
                            style: fontTextStyle(
                                16, const Color(0xFF7E7F80), FontWeight.w500),
                          ),
                          const SizedBox(height: 6),

                          // AMOUNT
                          Text(
                            '₹$collectAmountInRupees',
                            style: fontTextStyle(
                                24, const Color(0xFF343637), FontWeight.w600),
                          ),

                          const SizedBox(height: 16),

                          // --------------------------------------------
                          // 🔥 QR Code Box
                          // --------------------------------------------
                          Container(
                            decoration: BoxDecoration(
                              color: Colors.white,
                              borderRadius: BorderRadius.circular(12),
                              border: Border.all(color: const Color(0xFFE0E0E0)),
                            ),
                            padding: const EdgeInsets.all(12),
                            child: QrImageView(
                              data: qrData,
                              size: 200,
                              gapless: true,
                              backgroundColor: Colors.white,
                            ),
                          ),

                          const SizedBox(height: 18),

                          // CONTINUE BUTTON
                          SizedBox(
                            width: double.infinity,
                            height: 48,
                            child: ElevatedButton(
                              onPressed: () async {
                                AppSettings.preLoaderDialog(context);

                                bool isOnline =
                                await AppSettings.internetConnectivity();
                                if (!isOnline) {
                                  Navigator.of(context, rootNavigator: true).pop();
                                  AppSettings.longFailedToast(
                                      "Please Check Internet");
                                  return;
                                }

                                var payload = {
                                  "amount_paid": widget.details.amount_paid,
                                  "payment_mode": widget.details.payment_mode,
                                  "orderStatus": "completed",
                                  "deliveredDate": formatDeliveredDate(),
                                };

                                // 🔥 Call API
                                var response = await AppSettings.amountpaidByCustomer(
                                    widget.details.bookingid, payload);

                                Navigator.of(context, rootNavigator: true)
                                    .pop(); // CLOSE LOADER

                                if (response.isNotEmpty) {
                                  // Decode JSON
                                  var json = jsonDecode(response);

                                  if (json["status_code"] == 200) {

                                    Navigator.pushAndRemoveUntil(
                                      context,
                                      MaterialPageRoute(builder: (_) => AllOrders(navigationFrom:"")),
                                          (route) => false,
                                    );

                                    return;
                                  } else {}
                                  AppSettings.longFailedToast(
                                      json["msg"] ?? "Invalid OTP");
                                  return;
                                }
                                // TODO: Navigate home
                              },
                              style: ElevatedButton.styleFrom(
                                backgroundColor: Colors.black,
                                foregroundColor: Colors.white,
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(24),
                                ),
                              ),
                              child: Text(
                                'Continue to Home',
                                style: fontTextStyle(14, Colors.white, FontWeight.w600),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
              ),
            ),
          ));
  }
}
