import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:gen_rentals/Models/BillsModels/BillDetailsResponse.dart';
import 'package:gen_rentals/Utility/AppColors.dart';
import 'package:gen_rentals/Utility/Reusablewidgets.dart';
import 'package:provider/provider.dart';

import '../../Notifier/BillProvider.dart';
import '../DashboardScreen.dart';
import 'BillDetailScreen.dart';


class BillDetailListScreen extends StatefulWidget {
  final String sessionId;
  final String accId;
  final String orderId;

  BillDetailListScreen({
    super.key,
    required this.sessionId,
    required this.accId,
    required this.orderId,
  });

  @override
  State<BillDetailListScreen> createState() => _BillDetailListScreenState();
}

class _BillDetailListScreenState extends State<BillDetailListScreen> {
  @override
  void initState() {
    super.initState();
    Future.microtask(() {
      final provider = Provider.of<BillProvider>(context, listen: false);
      provider.fetchBillList(widget.sessionId, widget.orderId, widget.accId);
    });
  }

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

        final latest = provider.latestBill;
        final bills = provider.bills;

        return SafeArea(
          top: false,
          child: Scaffold(
            appBar: AppBar(
              automaticallyImplyLeading: false,
              backgroundColor: Colors.white,
              title: Row(
                children: [
                  InkResponse(
                    onTap: () => Navigator.pop(context, true),
                    child: SvgPicture.asset(
                      "assets/svg/continue_left_ic.svg",
                      height: 25,
                    ),
                  ),
                  const SizedBox(width: 10),
                  const Text(
                    "Bill List",
                    style: TextStyle(
                      fontSize: 16,
                      fontFamily: "Plus Jakarta Sans",
                      fontWeight: FontWeight.w400,
                      color: Colors.black87,
                    ),
                  ),
                ],
              ),
            ),
            backgroundColor: AppColors.backgroundRegular,
            body: RefreshIndicator.adaptive(
              color: AppColors.subtitleText,
              onRefresh: () async {
                final provider = Provider.of<BillProvider>(context, listen: false);
                await provider.fetchBillList(widget.sessionId, widget.orderId, widget.accId);
              },
              child: SingleChildScrollView(
                physics: const AlwaysScrollableScrollPhysics(),
                child: Container(
                  padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 14),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      SectionHeading(
                        title: 'Latest Bill',
                        textStyle: TextStyle(
                          fontFamily: "Poppins",
                          color: AppColors.normalText,
                          fontSize: 14,
                          fontWeight: FontWeight.w500,
                        ),
                        padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
                      ),
                      const SizedBox(height: 12),

                      // Latest Bill Card
                      if (latest != null)
                        InkResponse(
                          onTap: () {
                            Navigator.push(
                                context,
                                MaterialPageRoute(builder: (context) => BillDetailScreen(
                                  sessionId: widget.sessionId,
                                  accId: widget.accId,
                                  billId: latest.orderId.toString(),
                                ))
                            );
                          },
                          child: Container(
                            width: double.infinity,
                            padding: const EdgeInsets.all(20),
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(16),
                              gradient: const LinearGradient(
                                begin: Alignment.topLeft,
                                end: Alignment.bottomRight,
                                colors: [
                                  Color(0xFFE9FFDD),
                                  Color(0xFFB5FFD1),
                                ],
                              ),
                            ),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Row(
                                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                  children: [
                                    Text(
                                      "₹${latest.totalPrice ?? '0'}",
                                      style: TextStyle(
                                        fontFamily: "Poppins",
                                        color: AppColors.cardAmountText,
                                        fontSize: 34,
                                        fontWeight: FontWeight.w500,
                                      ),
                                    ),
                                    Container(
                                      padding: const EdgeInsets.symmetric(
                                          horizontal: 12, vertical: 6),
                                      decoration: BoxDecoration(
                                        borderRadius: BorderRadius.circular(12),
                                      ),
                                      child: Stack(
                                        children: [
                                          if(latest.billPaid == "Yes")
                                            Row(
                                              children: [
                                                SvgPicture.asset(
                                                  "assets/svg/success_ic.svg",
                                                  height: 18,
                                                  width: 18,
                                                ),
                                                const SizedBox(width: 6),
                                                const Text(
                                                  "Bill Paid",
                                                  style: TextStyle(
                                                    fontFamily: "Poppins",
                                                    color: Color(0xFF212121),
                                                    fontSize: 14,
                                                    fontStyle: FontStyle.normal,
                                                    fontWeight: FontWeight.w400,
                                                  ),
                                                ),
                                              ],
                                            ),
                                          // Pending
                                          // if(latest.billPaid == "No")
                                          //   InkResponse(
                                          //     onTap: () => showPaymentBottomSheet(context, payBill: "1299", payTotal: "4218"),
                                          //     child: Container(
                                          //       padding: const EdgeInsets.symmetric(
                                          //           horizontal: 12, vertical: 8),
                                          //       decoration: BoxDecoration(
                                          //         color: const Color(0xE0008CDE),
                                          //         borderRadius: BorderRadius.circular(14),
                                          //       ),
                                          //       child: const Text(
                                          //         "Pay Now",
                                          //         style: TextStyle(
                                          //           color: Colors.white,
                                          //           fontSize: 14,
                                          //           fontWeight: FontWeight.w500,
                                          //         ),
                                          //       ),
                                          //     ),
                                          //   ),
                                        ],
                                      ),
                                    ),
                                  ],
                                ),
                                const SizedBox(height: 16),
                                Container(
                                  height: 1,
                                  color: const Color(0xFF777777).withOpacity(0.3),
                                ),
                                const SizedBox(height: 12),
                                Row(
                                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                  children: [
                                    Text(
                                      "Invoice raised against",
                                      style: TextStyle(
                                        fontFamily: "Poppins",
                                        fontStyle: FontStyle.normal,
                                        color: AppColors.normalText,
                                        fontWeight: FontWeight.w400,
                                        fontSize: 14,
                                      ),
                                    ),
                                    Text(
                                      "#${latest.id ?? '-'}",
                                      style: TextStyle(
                                        fontFamily: "Poppins",
                                        fontStyle: FontStyle.normal,
                                        color: AppColors.amountText,
                                        fontWeight: FontWeight.w400,
                                        fontSize: 14,
                                      ),
                                    ),
                                  ],
                                ),
                                const SizedBox(height: 4),
                                Row(
                                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                  children: [
                                    Text(
                                      "Order ID: ${latest.orderId ?? '-'}",
                                      style: TextStyle(
                                        fontFamily: "Poppins",
                                        fontStyle: FontStyle.normal,
                                        color: AppColors.normalText,
                                        fontWeight: FontWeight.w400,
                                        fontSize: 14,
                                      ),
                                    ),
                                    Text(
                                      latest.billDate ?? '',
                                      style: TextStyle(
                                        fontStyle: FontStyle.normal,
                                        fontFamily: "Poppins",
                                        color: AppColors.normalText,
                                        fontWeight: FontWeight.w400,
                                        fontSize: 14,
                                      ),
                                    ),
                                  ],
                                ),
                              ],
                            ),
                          ),
                        )
                      else
                        const Center(child: Text("No Latest Bill Found")),

                      const SizedBox(height: 24),
                      SectionHeading(
                        title: 'All Previous Bills',
                        textStyle: TextStyle(
                          fontFamily: "Poppins",
                          color: AppColors.normalText,
                          fontSize: 14,
                          fontWeight: FontWeight.w500,
                        ),
                        padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
                      ),
                      const SizedBox(height: 8),

                      // ✅ Bill List
                      bills.isEmpty
                          ? const Padding(
                        padding: EdgeInsets.symmetric(vertical: 20),
                        child: Center(child: Text("No Previous Bills")),
                      )
                          : Column(
                        children: [
                          ...bills.map((bill) {
                            return Padding(
                              padding: const EdgeInsets.only(bottom: 8),
                              child: InkResponse(
                                onTap: () {
                                  Navigator.push(
                                    context,
                                    MaterialPageRoute(builder: (context) => BillDetailScreen(
                                      sessionId: widget.sessionId,
                                      accId: widget.accId,
                                      billId: bill.orderId.toString(),
                                    )),
                                  );
                                },
                                child: _buildBillItem(
                                  orderId: "#${bill.id ?? ''}",
                                  fromDate: bill.billDate ?? '',
                                  toDate: bill.billDate ?? '',
                                  amount: bill.totalPrice ?? '0',
                                ),
                              ),
                            );
                          }).toList(),
                          const SizedBox(height: 20), // Add some bottom padding
                        ],
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ),
        );
      },
    );
  }

  Widget _buildBillItem({
    String orderId = "#1253",
    String title = "Invoice raised against",
    required String fromDate,
    required String toDate,
    required String amount,
  }) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
      decoration: BoxDecoration(
        color: Colors.grey.shade50,
        borderRadius: BorderRadius.circular(18),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            orderId,
            style: TextStyle(
              fontFamily: "Poppins",
              color: AppColors.amountText,
              fontWeight: FontWeight.w400,
              fontStyle: FontStyle.normal,
              fontSize: 14,
            ),
          ),
          const SizedBox(height: 2),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                title,
                style: TextStyle(
                  fontFamily: "Poppins",
                  color: AppColors.normalText,
                  fontWeight: FontWeight.w400,
                  fontStyle: FontStyle.normal,
                  fontSize: 14,
                ),
              ),
              Text(
                fromDate,
                style: TextStyle(
                  fontFamily: "Poppins",
                  color: AppColors.subtitleText,
                  fontSize: 12,
                  fontStyle: FontStyle.normal,
                  fontWeight: FontWeight.w400,
                ),
              ),
            ],
          ),
          const SizedBox(height: 2),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                "Order ID : ${orderId.replaceAll('#', '')}",
                style: TextStyle(
                  fontFamily: "Poppins",
                  color: AppColors.normalText,
                  fontWeight: FontWeight.w400,
                  fontStyle: FontStyle.normal,
                  fontSize: 14,
                ),
              ),
              Text(
                "₹$amount",
                style: TextStyle(
                  fontFamily: "Poppins",
                  color: AppColors.cardAmountText,
                  fontSize: 14,
                  fontStyle: FontStyle.normal,
                  fontWeight: FontWeight.w400,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  void showPaymentBottomSheet(
      BuildContext context, {
        String? payTotal = "4218",
        String? payBill = "2018",
      }) {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true, // This is important
      backgroundColor: Colors.transparent,
      isDismissible: true,
      enableDrag: true,
      builder: (BuildContext context) {
        return PaymentBottomSheetContent(
          payTotal: payTotal,
          payBill: payBill,
          billFlag: true,
          partFlag: false,
        );
      },
    );
  }
}
