import 'package:flutter/material.dart';
import 'package:razorpay_flutter/razorpay_flutter.dart';
import 'package:upi_india/upi_india.dart';

class PaymentOptionsPage extends StatefulWidget {
  final double amount;
  const PaymentOptionsPage({required this.amount});

  @override
  State<PaymentOptionsPage> createState() => _PaymentOptionsPageState();
}

class _PaymentOptionsPageState extends State<PaymentOptionsPage> {
  late Razorpay _razorpay;
  late UpiIndia _upiIndia;
  List<UpiApp> upiApps = [];
  bool isFetching = true;

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

    _razorpay = Razorpay();
    _razorpay.on(Razorpay.EVENT_PAYMENT_SUCCESS, _handleRazorpaySuccess);
    _razorpay.on(Razorpay.EVENT_PAYMENT_ERROR, _handleRazorpayError);
    _razorpay.on(Razorpay.EVENT_EXTERNAL_WALLET, _handleExternalWallet);

    _upiIndia = UpiIndia();
    fetchUpiApps();
  }

  void fetchUpiApps() async {
    try {
      upiApps = await _upiIndia.getAllUpiApps(mandatoryTransactionId: false);
    } catch (e) {
      upiApps = [];
    }
    setState(() {
      isFetching = false;
    });
  }

  void _openRazorpay() {
    var options = {
      'key': 'rzp_test_1DP5mmOlF5G5ag', // Replace with your Razorpay key
      'amount': (widget.amount * 100).toInt(), // In paise
      'name': 'Water Supplier',
      'description': 'Advance Payment',
      'prefill': {
        'contact': '9876543210',
        'email': 'test@example.com',
      },
    };

    try {
      _razorpay.open(options);
    } catch (e) {
      print('Error: $e');
    }
  }

  void _startUpiTransaction(UpiApp app) async {
    UpiResponse response = await _upiIndia.startTransaction(
      app: app,
      receiverUpiId: 'yourupi@okaxis', // Replace with your real UPI ID
      receiverName: 'Water Supplier',
      transactionRefId: 'TXN${DateTime.now().millisecondsSinceEpoch}',
      transactionNote: 'Advance Payment',
      amount: widget.amount,
    );
    _handleUpiResponse(response);
  }

  void _handleUpiResponse(UpiResponse res) {
    String status = res.status?.toLowerCase() ?? "unknown";
    if (status == "success") {
      Navigator.pop(context);
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text("UPI Payment Successful")));
    } else if (status == "failure") {
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text("UPI Payment Failed")));
    } else {
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text("UPI Payment Cancelled")));
    }
  }

  void _handleRazorpaySuccess(PaymentSuccessResponse response) {
    Navigator.pop(context);
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text("Razorpay Payment Success")));
  }

  void _handleRazorpayError(PaymentFailureResponse response) {
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text("Razorpay Payment Failed")));
  }

  void _handleExternalWallet(ExternalWalletResponse response) {
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text("Wallet: ${response.walletName}")));
  }

  @override
  void dispose() {
    _razorpay.clear();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Choose Payment Option")),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            // Razorpay Button
            ElevatedButton.icon(
              onPressed: _openRazorpay,
              icon: Icon(Icons.credit_card),
              label: Text("Pay with Razorpay (Cards, UPI, Wallets)"),
              style: ElevatedButton.styleFrom(
                backgroundColor: Color(0xFF1D7AFC),
                padding: EdgeInsets.symmetric(vertical: 14),
                textStyle: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
              ),
            ),
            SizedBox(height: 24),
            Align(
              alignment: Alignment.centerLeft,
              child: Text(
                "Or choose a UPI App:",
                style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600),
              ),
            ),
            SizedBox(height: 12),
            Expanded(
              child: isFetching
                  ? Center(child: CircularProgressIndicator())
                  : upiApps.isEmpty
                  ? Center(child: Text("No UPI apps found"))
                  : ListView.builder(
                itemCount: upiApps.length,
                itemBuilder: (context, index) {
                  final app = upiApps[index];
                  return ListTile(
                    leading: Image.memory(app.icon, height: 40, width: 40),
                    title: Text(app.name),
                    onTap: () => _startUpiTransaction(app),
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}
