import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';

import 'package:provider/provider.dart';
import '../../Notifier/BillProvider.dart';
import '../../Utility/AppColors.dart';
import '../../Utility/Reusablewidgets.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<BillProvider>(context, listen: false);
      provider.fetchBillDetails(widget.sessionId, widget.accId, widget.billId);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<BillProvider>(
      builder: (context, provider, _) {
        if (provider.isDetailsLoading) {
          return const Scaffold(
            body: Center(child: CircularProgressIndicator()
),
          );
        }
        final details = provider.billDetails;
        if (details == null) {
          return Scaffold(
            body: Center(
              child: Text(
                provider.errorMessage ?? "No details found",
                style: const TextStyle(fontSize: 16),
              ),
            ),
          );
        }

        return SafeArea(
          top: false,
          child: Scaffold(
            appBar: AppBar(
              automaticallyImplyLeading: false,
              backgroundColor: Colors.white,
              elevation: 0,
              title: Row(
                children: [
                  InkResponse(
                    onTap: () => Navigator.pop(context, true),
                    child: SvgPicture.asset(
                      "assets/svg/continue_left_ic.svg",
                      height: 28,
                    ),
                  ),
                  const SizedBox(width: 10),
                  const Text(
                    "Bill Details",
                    style: TextStyle(
                      fontSize: 16,
                      fontFamily: "Plus Jakarta Sans",
                      fontWeight: FontWeight.w600,
                      color: Colors.black87,
                    ),
                  ),
                ],
              ),
            ),
            backgroundColor: Colors.white,
            body: SingleChildScrollView(
              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 20),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  // Green Tick Circle
                  Container(
                    height: 70,
                    width: 70,
                    decoration: const BoxDecoration(
                      color: Color(0xFFDFF8E1),
                      shape: BoxShape.circle,
                    ),
                    child: const Icon(
                      Icons.check_circle,
                      color: Colors.green,
                      size: 50,
                    ),
                  ),
                  const SizedBox(height: 16),

                  //  Bill Paid Title
                  const Text(
                    "Bill Paid",
                    style: TextStyle(
                      fontSize: 24,
                      fontFamily: "Poppins",
                      fontStyle: FontStyle.normal,
                      fontWeight: FontWeight.w400,
                    ),
                  ),

                  const SizedBox(height: 6),

                  //  Total Amount
                  Text(
                    "₹${details.totalPrice ?? "0"}",
                    style: const TextStyle(
                      fontSize: 34,
                      fontFamily: "Poppins",
                      fontWeight: FontWeight.w500,
                    ),
                  ),

                  const SizedBox(height: 24),

                  Divider(color: Colors.grey.shade300),

                  const SizedBox(height: 10),

                  //  Payment Details
                  Align(
                    alignment: Alignment.centerLeft,
                    child: Text(
                      "Payment Details",
                      style: TextStyle(
                        fontSize: 14,
                        fontWeight: FontWeight.w500,
                        color: Colors.black87,
                      ),
                    ),
                  ),
                  const SizedBox(height: 10),

                  _buildRow("Date", "${details.paidDate ?? ''}",
                      highlight: true),
                  // _buildRow(
                  //   "Date",
                  //   details.billDate != null
                  //       ? DateFormat("d MMM, yyyy").format(
                  //     DateTime.parse(details.billDate!),
                  //   )
                  //       : "-",
                  // ),

                  const SizedBox(height: 14),

                  //  Product Details
                  Align(
                    alignment: Alignment.centerLeft,
                    child: Text(
                      "Products",
                      style: TextStyle(
                        fontSize: 14,
                        fontFamily: "Plus Jakarta Sans",
                        fontWeight: FontWeight.w600,
                        color: Colors.grey.shade800,
                      ),
                    ),
                  ),
                  const SizedBox(height: 8),

                  _buildRow(details.product ?? "N/A", "₹${details.basicPrice ?? "0"}"),

                  const SizedBox(height: 8),

                  _buildRow("Sub Total", "₹${details.basicPrice ?? "0"}"),
                  _buildRow("Gross Amount", "₹${details.totalPrice ?? "0"}"),
                  _buildRow("SGST", details.sgst ?? "0"),
                  _buildRow("CGST", details.cgst ?? "0"),
                  _buildRow("IGST", details.igst ?? "0"),

                  const Divider(height: 30),

                  _buildRow(
                    "Total",
                    "₹${details.totalPrice ?? "0"}",
                    isBold: true,
                  ),

                  const SizedBox(height: 40),

                  //  Download Button


                ],
              ),
            ),
            bottomNavigationBar: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 14),
              child: SizedBox(
                width: double.infinity,
                child: ElevatedButton.icon(
                  onPressed: provider.isDownloading
                      ? null
                      : () {
                    provider.downloadBill(
                      context,
                      widget.sessionId,
                      widget.billId,
                      widget.accId,
                    );
                  },
                  icon: provider.isDownloading
                      ? const SizedBox(
                    width: 18,
                    height: 18,
                    child: CircularProgressIndicator(
                      color: Colors.white,
                      strokeWidth: 2,
                    ),
                  )
                      : const Icon(Icons.download, color: Colors.white),
                  label: Text(
                    provider.isDownloading
                        ? "Downloading..."
                        : "Download Receipt",
                    style: const TextStyle(
                      fontSize: 16,
                      fontFamily: "Plus Jakarta Sans",
                      fontWeight: FontWeight.w600,
                      color: Colors.white,
                    ),
                  ),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: AppColors.amountText,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(50),
                    ),
                    padding: const EdgeInsets.symmetric(vertical: 14),
                  ),
                ),
              ),
            ),
          ),
        );
      },
    );
  }

  /// Helper Row Widget
  Widget _buildRow(String title, String value,
      {bool isBold = false, bool highlight = false}) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Expanded(
            flex: 7,
            child: Text(
              title,
              maxLines: 2,
              style: TextStyle(
                fontSize: 14,
                fontFamily: "Plus Jakarta Sans",
                color: AppColors.subtitleText,
                fontWeight: FontWeight.w400,
              ),
            ),
          ),
          Text(
            value,
            style: TextStyle(
              fontSize: 14,
              fontFamily: "Plus Jakarta Sans",
              fontWeight: isBold ? FontWeight.w700 : FontWeight.w400,
              color: highlight
                  ? AppColors.normalText
                  : Colors.grey.shade900,
            ),
          ),
        ],
      ),
    );
  }
}
