
import 'package:bookmywages/consts_widgets/app_colors.dart';
import 'package:bookmywages/viewmodel/api_controller.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:intl/intl.dart';

class PaymentDetails extends ConsumerStatefulWidget {
  const PaymentDetails({super.key});

  @override
  ConsumerState<PaymentDetails> createState() => _PaymentDetailsState();
}

class _PaymentDetailsState extends ConsumerState<PaymentDetails> {
  List<dynamic> _localPayments = [];

  @override
  Widget build(BuildContext context) {
    final paymentAsync = ref.watch(paymentdetailsProvider);

    return Scaffold(
      backgroundColor: AppColors.secondprimary,
      body: paymentAsync.when(
        data: (payments) {
          final filteredPayments = payments.where((p) => p.type == 1).toList();

          // Initialize local copy only once
          if (_localPayments.isEmpty) {
            _localPayments = List.from(filteredPayments);
          }

          if (_localPayments.isEmpty) {
            return const Center(child: Text("No payment history found."));
          }

          return RefreshIndicator(
            onRefresh: () async {
              final refreshed = await ref.refresh(
                paymentdetailsProvider.future,
              );
              setState(() {
                _localPayments = refreshed.where((p) => p.type == 2).toList();
              });
            },
            child: ListView.builder(
              itemCount: _localPayments.length,
              itemBuilder: (context, index) {
                final payment = _localPayments[index];
                return Dismissible(
                  key: Key(payment.id.toString()),
                  direction: DismissDirection.endToStart,
                  background: Container(
                    margin: const EdgeInsets.symmetric(
                      horizontal: 16,
                      vertical: 8,
                    ),
                    decoration: BoxDecoration(
                      color: Colors.red,
                      borderRadius: BorderRadius.circular(20),
                    ),
                    alignment: Alignment.centerRight,
                    padding: const EdgeInsets.only(right: 20),
                    child: const Icon(Icons.delete, color: Colors.white),
                  ),
                  confirmDismiss: (direction) async {
                    return await showDialog(
                      context: context,
                      builder: (BuildContext context) {
                        return AlertDialog(
                          title: const Text("Confirm Delete"),
                          content: const Text(
                            "Are you sure you want to delete this payment record?",
                          ),
                          actions: <Widget>[
                            TextButton(
                              onPressed: () => Navigator.of(context).pop(false),
                              child: const Text("CANCEL"),
                            ),
                            TextButton(
                              onPressed: () => Navigator.of(context).pop(true),
                              child: const Text(
                                "DELETE",
                                style: TextStyle(color: Colors.red),
                              ),
                            ),
                          ],
                        );
                      },
                    );
                  },
                  onDismissed: (direction) async {
                    Fluttertoast.showToast(
                      msg: 'Deleting payment...',
                      toastLength: Toast.LENGTH_SHORT,
                      gravity: ToastGravity.BOTTOM,
                      backgroundColor: Colors.grey,
                      textColor: Colors.white,
                    );

                    final success = await ref.read(
                      paymentdeleteProvider(payment.id.toString()).future,
                    );

                    if (success) {
                      setState(() {
                        _localPayments.removeAt(index);
                      });

                      Fluttertoast.showToast(
                        msg: '${payment.planName} deleted successfully',
                        toastLength: Toast.LENGTH_SHORT,
                        gravity: ToastGravity.BOTTOM,
                        backgroundColor: Colors.green,
                        textColor: Colors.white,
                      );
                    } else {
                      Fluttertoast.showToast(
                        msg: 'Failed to delete payment',
                        toastLength: Toast.LENGTH_SHORT,
                        gravity: ToastGravity.BOTTOM,
                        backgroundColor: Colors.red,
                        textColor: Colors.white,
                      );
                    }
                  },

                  child: Container(
                    margin: const EdgeInsets.symmetric(
                      horizontal: 16,
                      vertical: 8,
                    ),
                    padding: const EdgeInsets.all(16),
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(20),
                      border: Border.all(
                        color: const Color(0xFFCFCFCF),
                        width: 1,
                      ),
                    ),
                    child: IntrinsicHeight(
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.stretch,
                        children: [
                          Container(
                            width: 130,
                            padding: const EdgeInsets.all(16),
                            decoration: BoxDecoration(
                              color: const Color(0xFF334E95),
                              borderRadius: BorderRadius.circular(12.86),
                              border: Border.all(
                                color: Colors.white,
                                width: 0.43,
                              ),
                              boxShadow: [
                                BoxShadow(
                                  color: const Color(0x40828282),
                                  blurRadius: 1.71,
                                  offset: const Offset(0, 2.14),
                                ),
                              ],
                            ),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Center(
                                  child: Text(
                                    payment.planName,
                                    style: const TextStyle(
                                      fontFamily: 'Gilroy-Bold',
                                      fontWeight: FontWeight.w700,
                                      fontSize: 14,
                                      height: 1.0,
                                      letterSpacing: 0.1371,
                                      color: Colors.white,
                                    ),
                                    textAlign: TextAlign.center,
                                    maxLines: 1,
                                    overflow: TextOverflow.ellipsis,
                                  ),
                                ),
                                const SizedBox(height: 15),
                                Row(
                                  children: [
                                    Container(
                                      width: 6.86,
                                      height: 6.86,
                                      decoration: const BoxDecoration(
                                        color: Color(0xFFF9E369),
                                        shape: BoxShape.circle,
                                      ),
                                    ),
                                    const SizedBox(width: 8),
                                    Expanded(
                                      child: Text(
                                        _formatDuration(payment.duration),
                                        style: const TextStyle(
                                          fontFamily: 'Gilroy-Medium',
                                          fontWeight: FontWeight.w400,
                                          fontSize: 12,
                                          height: 1.0,
                                          letterSpacing: 0.0771,
                                          color: Colors.white,
                                        ),
                                        overflow: TextOverflow.ellipsis,
                                      ),
                                    ),
                                  ],
                                ),
                                const SizedBox(height: 10),
                                Row(
                                  children: [
                                    Container(
                                      width: 6.86,
                                      height: 6.86,
                                      decoration: const BoxDecoration(
                                        color: Color(0xFFF9E369),
                                        shape: BoxShape.circle,
                                      ),
                                    ),
                                    const SizedBox(width: 8),
                                    Expanded(
                                      child: Text(
                                        payment.description,
                                        style: const TextStyle(
                                          fontFamily: 'Gilroy-Medium',
                                          fontWeight: FontWeight.w400,
                                          fontSize: 12,
                                          height: 1.0,
                                          letterSpacing: 0.0771,
                                          color: Colors.white,
                                        ),
                                        maxLines: 2,
                                        overflow: TextOverflow.ellipsis,
                                      ),
                                    ),
                                  ],
                                ),
                                const Divider(color: Colors.white),
                                Center(
                                  child: Text(
                                    _formatPrice(payment.price),
                                    style: const TextStyle(
                                      fontWeight: FontWeight.bold,
                                      color: Colors.white,
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                          const SizedBox(width: 12),
                          Expanded(
                            child: Padding(
                              padding: const EdgeInsets.symmetric(vertical: 10),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(
                                    payment.planName,
                                    style: const TextStyle(
                                      fontFamily: 'Gilroy-Bold',
                                      fontWeight: FontWeight.w700,
                                      fontSize: 19.9,
                                      height: 1.0,
                                      letterSpacing: 0.199,
                                      color: Colors.black,
                                    ),
                                    maxLines: 1,
                                    overflow: TextOverflow.ellipsis,
                                  ),
                                  const SizedBox(height: 10),
                                  Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceBetween,
                                    children: [
                                      Column(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        children: [
                                          const Text(
                                            "Start :",
                                            style: TextStyle(
                                              fontFamily: 'Gilroy-Bold',
                                              fontWeight: FontWeight.w700,
                                              fontSize: 15.61,
                                              height: 14.04 / 15.61,
                                              letterSpacing: 0.0,
                                              color: Colors.black,
                                            ),
                                          ),
                                          const SizedBox(height: 10),
                                          Text(
                                            DateFormat('MMM d, y').format(
                                              DateTime.parse(
                                                payment.createdDate,
                                              ),
                                            ),
                                            style: const TextStyle(
                                              fontFamily: 'Gilroy-Medium',
                                              fontWeight: FontWeight.w700,
                                              fontSize: 12,
                                              height: 14.04 / 15.61,
                                              letterSpacing: 0.0,
                                              color: Color(0xFF636363),
                                            ),
                                          ),
                                        ],
                                      ),
                                      Column(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        children: [
                                          const Text(
                                            "End :",
                                            style: TextStyle(
                                              fontFamily: 'Gilroy-Bold',
                                              fontWeight: FontWeight.w700,
                                              fontSize: 15.61,
                                              height: 14.04 / 15.61,
                                              letterSpacing: 0.0,
                                              color: Colors.black,
                                            ),
                                          ),
                                          const SizedBox(height: 10),
                                          Text(
                                            DateFormat('MMM d, y').format(
                                              DateTime.parse(payment.endDate),
                                            ),
                                            style: const TextStyle(
                                              fontFamily: 'Gilroy-Medium',
                                              fontWeight: FontWeight.w700,
                                              fontSize: 12,
                                              height: 14.04 / 15.61,
                                              letterSpacing: 0.0,
                                              color: Color(0xFF636363),
                                            ),
                                          ),
                                        ],
                                      ),
                                    ],
                                  ),
                                  const SizedBox(height: 10),
                                  Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceBetween,
                                    children: [
                                      Column(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        children: [
                                          const Text(
                                            "Time :",
                                            style: TextStyle(
                                              fontFamily: 'Gilroy-Bold',
                                              fontWeight: FontWeight.w700,
                                              fontSize: 15.61,
                                              height: 14.04 / 15.61,
                                              letterSpacing: 0.0,
                                              color: Colors.black,
                                            ),
                                          ),
                                          const SizedBox(height: 10),
                                          Text(
                                            DateFormat('hh:mm a').format(
                                              DateTime.parse(
                                                payment.createdDate,
                                              ),
                                            ),
                                            style: const TextStyle(
                                              fontFamily: 'Gilroy-Medium',
                                              fontWeight: FontWeight.w700,
                                              fontSize: 12,
                                              height: 14.04 / 15.61,
                                              letterSpacing: 0.0,
                                              color: Color(0xFF636363),
                                            ),
                                          ),
                                        ],
                                      ),
                                      Column(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        children: [
                                          const Text(
                                            "Payment :",
                                            style: TextStyle(
                                              fontFamily: 'Gilroy-Bold',
                                              fontWeight: FontWeight.w700,
                                              fontSize: 15.61,
                                              height: 14.04 / 15.61,
                                              letterSpacing: 0.0,
                                              color: Colors.black,
                                            ),
                                          ),
                                          const SizedBox(height: 10),
                                          Text(
                                            _formatPrice(payment.price),
                                            style: const TextStyle(
                                              fontFamily: 'Gilroy-Medium',
                                              fontWeight: FontWeight.w700,
                                              fontSize: 12,
                                              height: 14.04 / 15.61,
                                              letterSpacing: 0.0,
                                              color: Color(0xFF636363),
                                            ),
                                          ),
                                        ],
                                      ),
                                    ],
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                );
              },
            ),
          );
        },
        loading: () => const Center(child: CircularProgressIndicator()),
        error: (e, _) => Center(child: Text("Error: ${e.toString()}")),
      ),
    );
  }

  static String _formatDuration(int days) {
    if (days == 30) return '1 Month';
    if (days == 60) return '2 Months';
    if (days == 90) return '3 Months';
    if (days == 180) return '6 Months';
    if (days == 365) return '1 Year';
    return '$days Days';
  }

  static String _formatPrice(String price) {
    if (price.startsWith('Rs.')) {
      return price;
    }
    return 'Rs.$price';
  }
}
