import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:gen_service/Notifiers/TransactionsProvider.dart';
import '../../Utility/AppColors.dart';
import '../../Utility/CustomSnackbar.dart';

class BillDetailScreen extends StatefulWidget {
  final String sessionId;
  final String accId;
  final String billId;

  const BillDetailScreen({
    super.key,
    required this.sessionId,
    required this.accId,
    required this.billId,
  });

  @override
  State<BillDetailScreen> createState() => _BillDetailScreenState();
}

class _BillDetailScreenState extends State<BillDetailScreen> {
  @override
  void initState() {
    super.initState();
    Future.microtask(() {
      final provider = Provider.of<TransactionsProvider>(context, listen: false);
      provider.fetchBillDetails(widget.accId, widget.sessionId, widget.billId);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<TransactionsProvider>(
      builder: (context, provider, _) {
        if (provider.isBillLoading) {
          return const Scaffold(
            body: Center(child: CircularProgressIndicator()),
          );
        }

        final billResponse = provider.billDetail;
        final details = billResponse?.billDetails;
        final products = billResponse?.billProducts ?? [];

        if (details == null) {
          return const Scaffold(
            body: Center(child: Text("No Bill Details Found")),
          );
        }

        return Scaffold(
          appBar: AppBar(
            backgroundColor: Colors.white,
            elevation: 0,
            title: const Text(
              "Bill Details",
              style: TextStyle(
                color: Colors.black87,
                fontFamily: "Poppins",
                fontWeight: FontWeight.w600,
              ),
            ),
            leading: IconButton(
              icon: const Icon(Icons.arrow_back_ios_new, color: Colors.black87),
              onPressed: () => Navigator.pop(context),
            ),
          ),
          backgroundColor: Colors.white,
          body: SingleChildScrollView(
            padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 14),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                // 🔔 Pending Icon
                Container(
                  height: 70,
                  width: 70,
                  decoration: const BoxDecoration(
                    color: Color(0xFFFFEBEB),
                    shape: BoxShape.circle,
                  ),
                  child: const Icon(
                    Icons.access_time,
                    color: Colors.redAccent,
                    size: 44,
                  ),
                ),
                const SizedBox(height: 14),

                // 💰 Amount
                Text(
                  "₹${details.totalAmount ?? "0"}",
                  style: const TextStyle(
                    fontSize: 32,
                    fontFamily: "Poppins",
                    fontWeight: FontWeight.w600,
                    color: Colors.black,
                  ),
                ),
                const SizedBox(height: 6),

                const Text(
                  "Pending Balance",
                  style: TextStyle(
                    fontSize: 15,
                    fontFamily: "Poppins",
                    color: Colors.black54,
                  ),
                ),
                const SizedBox(height: 8),

                const SizedBox(height: 16),
                const Divider(thickness: 1, color: Color(0xFFE6E6E6)),
                _buildSectionTitle("Product Names"),
                // 🧾 Product Names
                if (products.isNotEmpty)
                  Column(
                    children: products
                        .map(
                          (product) => Padding(
                        padding: const EdgeInsets.symmetric(vertical: 2),
                        child: _buildProductItem(
                          product.partName.toString(),
                          product.qty.toString(),
                          product.price.toString(),
                          product.totalPrice.toString()
                        )
                      ),
                    )
                        .toList(),
                  ),

                const SizedBox(height: 16),
                const Divider(thickness: 1, color: Color(0xFFE6E6E6)),
                const SizedBox(height: 8),

                // 📄 Bill Details
                _buildSectionTitle("Bill Details"),
                _buildRow("Date", details.createdDate ?? "--"),
                _buildRow("Complaint ID", "#${details.compId ?? "--"}",
                    highlight: true),
                _buildRow("Raise Against", details.raisedAgainst ?? "--"),

                const SizedBox(height: 14),
                const Divider(thickness: 1, color: Color(0xFFE6E6E6)),
                const SizedBox(height: 8),

                // 💸 Amount Details
                _buildSectionTitle("Amount Details"),
                _buildRow("Basic Amount", "₹${details.basicAmount ?? "0"}"),
                _buildRow("CGST Amount", "₹${details.cgst ?? "0"}"),
                _buildRow("SGST Amount", "₹${details.sgst ?? "0"}"),
                _buildRow("IGST Amount", "₹${details.igst ?? "0"}"),

                const SizedBox(height: 14),
                const Divider(thickness: 1, color: Color(0xFFE6E6E6)),
                const SizedBox(height: 8),

                // 🧾 Bill Summary
                _buildSectionTitle("Bill Summary"),
                _buildRow("Bill Balance Amount",
                    "₹${details.balancePaymentAmount ?? "0"}"),

                const SizedBox(height: 24),

                // Buttons Row
                Row(
                  children: [
                    // Expanded(
                    //   child: OutlinedButton.icon(
                    //     onPressed: provider.isDownloading
                    //         ? null
                    //         : () {
                    //       provider.downloadBill(
                    //         context,
                    //         widget.sessionId,
                    //         widget.billId,
                    //         widget.accId,
                    //       );
                    //     },
                    //     style: OutlinedButton.styleFrom(
                    //       padding: const EdgeInsets.symmetric(vertical: 14),
                    //       shape: RoundedRectangleBorder(
                    //         borderRadius: BorderRadius.circular(10),
                    //       ),
                    //       side: const BorderSide(color: Color(0xFF2563EB)),
                    //     ),
                    //     icon: const Icon(Icons.download,
                    //         color: Color(0xFF2563EB)),
                    //     label: const Text(
                    //       "Download",
                    //       style: TextStyle(
                    //         color: Color(0xFF2563EB),
                    //         fontFamily: "Poppins",
                    //         fontWeight: FontWeight.w600,
                    //       ),
                    //     ),
                    //   ),
                    // ),
                    const SizedBox(width: 12),
                    Expanded(
                      child: ElevatedButton(
                        onPressed: () {
                          // TODO: integrate Razorpay or Payment logic here
                        },
                        style: ElevatedButton.styleFrom(
                          backgroundColor: const Color(0xFF2563EB),
                          padding: const EdgeInsets.symmetric(vertical: 14),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(10),
                          ),
                        ),
                        child: const Text(
                          "Pay Now",
                          style: TextStyle(
                            color: Colors.white,
                            fontFamily: "Poppins",
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  // 🔹 Helper for Section Titles
  Widget _buildSectionTitle(String title) {
    return Align(
      alignment: Alignment.centerLeft,
      child: Text(
        title,
        style: const TextStyle(
          fontSize: 15,
          fontFamily: "Poppins",
          fontWeight: FontWeight.w600,
          color: Colors.black,
        ),
      ),
    );
  }

  // 🔹 Helper for Key-Value Rows
  Widget _buildRow(String title, String value, {bool highlight = false}) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 6),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            title,
            style: const TextStyle(
              fontSize: 14,
              fontFamily: "Poppins",
              color: Colors.black54,
            ),
          ),
          Text(
            value,
            style: TextStyle(
              fontSize: 14,
              fontFamily: "Poppins",
              fontWeight: highlight ? FontWeight.w600 : FontWeight.w400,
              color:
              highlight ? const Color(0xFF2563EB) : Colors.black87,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildProductItem(
      String partName, String price, String qty, String totalPrice) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 6),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          // Product name
          Expanded(
            flex: 3,
            child: Text(
              partName,
              maxLines: 2,
              style: const TextStyle(
                fontSize: 14,
                fontFamily: "Poppins",
                fontWeight: FontWeight.w500,
                color: Colors.black87,
              ),
              overflow: TextOverflow.ellipsis,
            ),
          ),

          // Qty × Price
          Expanded(
            flex: 1,
            child: Text(
              "$qty X ₹$price",
              textAlign: TextAlign.center,
              style: const TextStyle(
                fontSize: 14,
                fontFamily: "Poppins",
                color: Colors.black54,
              ),
            ),
          ),

          // Total Price
          Expanded(
            flex: 1,
            child: Text(
              "₹$totalPrice",
              textAlign: TextAlign.end,
              style: const TextStyle(
                fontSize: 14,
                fontFamily: "Poppins",
                fontWeight: FontWeight.bold,
                color: Colors.black87,
              ),
            ),
          ),
        ],
      ),
    );
  }

}
