// ignore_for_file: use_build_context_synchronously, deprecated_member_use, sort_child_properties_last

import 'package:academy_lms_app/constants.dart';

import 'package:flutter/material.dart';
import 'package:pdf/pdf.dart';
import 'package:provider/provider.dart';

import '../providers/purchase_history_provider.dart';
import 'purchase_history_invoice.dart';

import 'package:pdf/widgets.dart' as pw;
import 'package:printing/printing.dart';

class PurchaseHistoryScreen extends StatefulWidget {
  const PurchaseHistoryScreen({super.key});

  @override
  State<PurchaseHistoryScreen> createState() => _PurchaseHistoryScreenState();
}

class _PurchaseHistoryScreenState extends State<PurchaseHistoryScreen> {
  int? _expandedIndex;

  @override
  void initState() {
    super.initState();
    Future.microtask(
      () => Provider.of<PurchaseHistoryProvider>(
        context,
        listen: false,
      ).fetchPurchaseHistory(),
    );
  }

  Color getStatusColor(String? status) {
    if (status == null) return Colors.grey;

    switch (status.toLowerCase()) {
      case 'paid':
        return Colors.green;
      case 'pending':
        return Colors.orange;
      case 'failed':
        return Colors.red;
      default:
        return Colors.green;
    }
  }

  pw.Widget _pdfInfoRow(String title, String value) {
    return pw.Padding(
      padding: const pw.EdgeInsets.only(bottom: 12),
      child: pw.Row(
        crossAxisAlignment: pw.CrossAxisAlignment.start,
        children: [
          pw.Expanded(
            flex: 4,
            child: pw.Text(title, style: const pw.TextStyle(fontSize: 12)),
          ),
          pw.Text(" : "),
          pw.Expanded(
            flex: 6,
            child: pw.Text(
              value,
              style: pw.TextStyle(fontSize: 12, fontWeight: pw.FontWeight.bold),
            ),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final provider = Provider.of<PurchaseHistoryProvider>(context);

    if (provider.isLoading) {
      return const Scaffold(body: Center(child: CircularProgressIndicator()));
    }

    if (provider.items.isEmpty) {
      return const Scaffold(
        body: Center(child: Text("No Purchase History Found")),
      );
    }

    return Scaffold(
      appBar: AppBar(
        title: Text(
          'Purchase History',
          style: const TextStyle(fontSize: 22, fontWeight: FontWeight.w500),
        ),
      ),

      backgroundColor: kBackGroundColor,

      body: ListView.builder(
        padding: const EdgeInsets.all(16),
        itemCount: provider.items.length,
        itemBuilder: (context, index) {
          final purchaseHistory = provider.items[index];
          final isExpanded = _expandedIndex == index;

          return GestureDetector(
            onTap: () {
              setState(() {
                _expandedIndex = isExpanded ? null : index;
              });
            },
            // color: Colors.transparent,
            child: Container(
              margin: const EdgeInsets.only(bottom: 16),
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                border: Border.all(color: kAppButtonBorderColor),
                borderRadius: BorderRadius.circular(8),
              ),

              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        "Title :",
                        style: const TextStyle(fontWeight: FontWeight.bold),
                      ),
                      SizedBox(width: 4),
                      Expanded(
                        child: Text(
                          purchaseHistory.courseTitle ?? '',
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: const TextStyle(fontWeight: FontWeight.bold),
                        ),
                      ),
                    ],
                  ),

                  SizedBox(height: 8),

                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        "${purchaseHistory.currency} ${purchaseHistory.amount}",
                        style: const TextStyle(fontWeight: FontWeight.w500),
                      ),
                      Container(
                        padding: const EdgeInsets.symmetric(
                          horizontal: 10,
                          vertical: 2,
                        ),
                        decoration: BoxDecoration(
                          color: getStatusColor(
                            purchaseHistory.paymentType,
                          ).withOpacity(.15),
                          borderRadius: BorderRadius.circular(25),
                        ),
                        child: Text(
                          purchaseHistory.paymentType ?? '',
                          style: TextStyle(
                            fontWeight: FontWeight.bold,
                            color: getStatusColor(purchaseHistory.paymentType),
                          ),
                        ),
                      ),
                    ],
                  ),

                  if (isExpanded) ...[
                    SizedBox(height: 15),
                    Row(
                      children: [
                        Expanded(
                          child: OutlinedButton(
                            onPressed: () {
                              Navigator.push(
                                context,
                                MaterialPageRoute(
                                  builder: (_) => PurchaseHistoryInvoice(
                                    id: purchaseHistory.id,
                                    createdAt: purchaseHistory.createdAt,
                                    courseTitle: purchaseHistory.courseTitle,
                                    paymentType: purchaseHistory.paymentType,
                                    currency: purchaseHistory.currency
                                        ?.toString(),
                                    amount: purchaseHistory.amount?.toDouble(),
                                  ),
                                ),
                              );
                            },
                            child: Text("View Invoice"),
                            style: OutlinedButton.styleFrom(
                              elevation: 0,
                              shadowColor: Colors.transparent,
                              foregroundColor: Colors.black,
                              side: BorderSide(color: Color(0XFFD8DADA)),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(8),
                              ),
                              padding: EdgeInsets.symmetric(vertical: 10),
                            ),
                          ),
                        ),
                        SizedBox(width: 12),
                        Expanded(
                          child: ElevatedButton(
                            onPressed: () async {
                              final pdf = pw.Document();

                              pdf.addPage(
                                pw.Page(
                                  margin: const pw.EdgeInsets.all(32),
                                  build: (context) {
                                    return pw.Column(
                                      crossAxisAlignment:
                                          pw.CrossAxisAlignment.start,
                                      children: [
                                        /// HEADER
                                        pw.Container(
                                          width: double.infinity,
                                          padding:
                                              const pw.EdgeInsets.symmetric(
                                                vertical: 12,
                                              ),
                                          decoration: const pw.BoxDecoration(
                                            border: pw.Border(
                                              bottom: pw.BorderSide(width: 1),
                                            ),
                                          ),
                                          child: pw.Text(
                                            "INVOICE",
                                            textAlign: pw.TextAlign.center,
                                            style: pw.TextStyle(
                                              fontSize: 22,
                                              fontWeight: pw.FontWeight.bold,
                                            ),
                                          ),
                                        ),

                                        pw.SizedBox(height: 25),

                                        /// INVOICE BOX
                                        pw.Container(
                                          padding: const pw.EdgeInsets.all(16),
                                          decoration: pw.BoxDecoration(
                                            border: pw.Border.all(width: 1),
                                            borderRadius:
                                                pw.BorderRadius.circular(5),
                                          ),
                                          child: pw.Column(
                                            children: [
                                              _pdfInfoRow(
                                                "ID",
                                                purchaseHistory.id.toString(),
                                              ),
                                              _pdfInfoRow(
                                                "Date",
                                                purchaseHistory.createdAt ?? '',
                                              ),
                                              _pdfInfoRow(
                                                "Item",
                                                purchaseHistory.courseTitle ??
                                                    '',
                                              ),
                                              _pdfInfoRow(
                                                "Payment Method",
                                                purchaseHistory.paymentType ??
                                                    '',
                                              ),

                                              _pdfInfoRow(
                                                "Total Amount",
                                                "${purchaseHistory.amount ?? ''}",
                                              ),
                                            ],
                                          ),
                                        ),

                                        pw.SizedBox(height: 40),

                                        pw.Center(
                                          child: pw.Text(
                                            "Thank you for your purchase!",
                                            style: const pw.TextStyle(
                                              fontSize: 11,
                                            ),
                                          ),
                                        ),
                                      ],
                                    );
                                  },
                                ),
                              );

                              await Printing.layoutPdf(
                                onLayout: (PdfPageFormat format) async =>
                                    pdf.save(),
                              );
                            },
                            child: Text("Print Invoice"),
                            style: ElevatedButton.styleFrom(
                              elevation: 0,
                              shadowColor: Colors.transparent,
                              foregroundColor: kWhiteColor,
                              backgroundColor: kDefaultColor,
                              side: BorderSide(color: kDefaultColor),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(8),
                              ),
                              padding: EdgeInsets.symmetric(vertical: 10),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ],
                ],
              ),
            ),
          );
        },
      ),
    );
  }
}
