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),
              ),
            ),
          );
        }

        final bool isPaid = details.billPaid == "Yes";

        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: [
                  // Status Icon
                  Container(
                    height: 70,
                    width: 70,
                    decoration: BoxDecoration(
                      color: isPaid ? const Color(0xFFDFF8E1) : const Color(0xFFFFEBEB),
                      shape: BoxShape.circle,
                    ),
                    child: Icon(
                      isPaid ? Icons.check_circle : Icons.access_time_filled,
                      color: isPaid ? Colors.green : Colors.redAccent,
                      size: isPaid ? 50 : 40,
                    ),
                  ),
                  const SizedBox(height: 16),

                  // Status Title
                  Text(
                    isPaid ? "Bill Paid" : "Bill Pending",
                    style: const 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
                  const 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),
                  const SizedBox(height: 14),

                  // Product Details
                  const Align(
                    alignment: Alignment.centerLeft,
                    child: Text(
                      "Products",
                      style: TextStyle(
                        fontSize: 14,
                        fontFamily: "Plus Jakarta Sans",
                        fontWeight: FontWeight.w600,
                        color: Colors.black87,
                      ),
                    ),
                  ),
                  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),
                ],
              ),
            ),
            bottomNavigationBar: _buildBottomButtons(provider, isPaid),
          ),
        );
      },
    );
  }

  /// Conditional Bottom Buttons based on payment status
  Widget _buildBottomButtons(BillProvider provider, bool isPaid) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            blurRadius: 10,
            offset: const Offset(0, -2),
          ),
        ],
      ),
      child: Row(
        children: [
          // Pay Now Button (only if not paid)
          if (!isPaid) ...[
            Expanded(
              child: ElevatedButton(
                onPressed: () {
                  _showPayNowDialog();
                },
                style: ElevatedButton.styleFrom(
                  backgroundColor: AppColors.buttonColor,
                  foregroundColor: Colors.white,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(12),
                  ),
                  padding: const EdgeInsets.symmetric(vertical: 16),
                  elevation: 0,
                ),
                child: const Text(
                  "Pay Now",
                  style: TextStyle(
                    fontSize: 16,
                    fontFamily: "Plus Jakarta Sans",
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ),
            ),
            const SizedBox(width: 12),
          ],

          // Download Receipt Button
          Expanded(
            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, size: 20, 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(12),
                ),
                padding: const EdgeInsets.symmetric(vertical: 16),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// Pay Now Dialog
  void _showPayNowDialog() {
    showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          backgroundColor: Colors.white,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(20),
          ),
          title: Column(
            children: [
              Container(
                width: 60,
                height: 60,
                decoration: BoxDecoration(
                  color: AppColors.buttonColor.withOpacity(0.1),
                  shape: BoxShape.circle,
                ),
                child: Icon(
                  Icons.payment_rounded,
                  color: AppColors.buttonColor,
                  size: 30,
                ),
              ),
              const SizedBox(height: 16),
              const Text(
                "Pay Now",
                style: TextStyle(
                  fontFamily: "Plus Jakarta Sans",
                  fontWeight: FontWeight.w700,
                  fontSize: 20,
                  color: Colors.black87,
                ),
              ),
            ],
          ),
          content: const Text(
            "Proceed with payment for this bill?",
            textAlign: TextAlign.center,
            style: TextStyle(
              fontFamily: "Plus Jakarta Sans",
              fontSize: 14,
              fontWeight: FontWeight.w400,
              color: Colors.grey,
            ),
          ),
          actions: [
            Row(
              children: [
                // Cancel Button
                Expanded(
                  child: OutlinedButton(
                    onPressed: () => Navigator.pop(context),
                    style: OutlinedButton.styleFrom(
                      backgroundColor: Colors.transparent,
                      foregroundColor: Colors.grey[600],
                      side: BorderSide(
                        color: Colors.grey[300]!,
                        width: 1.5,
                      ),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(12),
                      ),
                      padding: const EdgeInsets.symmetric(vertical: 14),
                    ),
                    child: const Text(
                      "Cancel",
                      style: TextStyle(
                        fontFamily: "Plus Jakarta Sans",
                        fontWeight: FontWeight.w600,
                        fontSize: 14,
                      ),
                    ),
                  ),
                ),
                const SizedBox(width: 12),
                // Proceed Button
                Expanded(
                  child: ElevatedButton(
                    onPressed: () {
                      Navigator.pop(context);
                      _processPayment();
                    },
                    style: ElevatedButton.styleFrom(
                      backgroundColor: AppColors.buttonColor,
                      foregroundColor: Colors.white,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(12),
                      ),
                      padding: const EdgeInsets.symmetric(vertical: 14),
                    ),
                    child: const Text(
                      "Proceed",
                      style: TextStyle(
                        fontFamily: "Plus Jakarta Sans",
                        fontWeight: FontWeight.w600,
                        fontSize: 14,
                        color: Colors.white,
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ],
        );
      },
    );
  }

  /// Process Payment Method
  void _processPayment() {
    // Show loading
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => Center(
        child: Container(
          padding: const EdgeInsets.all(20),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(16),
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              CircularProgressIndicator(
                color: AppColors.buttonColor,
                strokeWidth: 3,
              ),
              const SizedBox(height: 16),
              const Text(
                "Processing Payment...",
                style: TextStyle(
                  fontFamily: "Plus Jakarta Sans",
                  fontWeight: FontWeight.w500,
                ),
              ),
            ],
          ),
        ),
      ),
    );

    // Simulate payment processing
    Future.delayed(const Duration(seconds: 2), () {
      Navigator.pop(context); // Close loading

      // Show success message
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          backgroundColor: Colors.green,
          content: Row(
            children: [
              const Icon(Icons.check_circle, color: Colors.white, size: 20),
              const SizedBox(width: 8),
              const Text(
                "Payment Successful!",
                style: TextStyle(
                  fontFamily: "Plus Jakarta Sans",
                  fontWeight: FontWeight.w500,
                ),
              ),
            ],
          ),
          duration: const Duration(seconds: 3),
          behavior: SnackBarBehavior.floating,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(8),
          ),
        ),
      );

      // Refresh bill details
      final provider = Provider.of<BillProvider>(context, listen: false);
      provider.fetchBillDetails(widget.sessionId, widget.accId, widget.billId);
    });
  }

  /// 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,
            ),
          ),
        ],
      ),
    );
  }
}
