import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:dotted_border/dotted_border.dart';
import 'package:bookatanker/supplier/paymnets/credit_accounts.dart';
import 'package:bookatanker/supplier/paymnets/transaction_model.dart';
import 'package:bookatanker/supplier/paymnets/transactions.dart';
import 'package:http/http.dart' as http;
import '../../common/settings.dart';

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

  @override
  State<PaymentsMainScreen> createState() => _PaymentsMainScreenState();
}

class _PaymentsMainScreenState extends State<PaymentsMainScreen> {

  List<TransactionModel> transactions = [];
  bool isLoading = true;

  Future<void> fetchTransactions() async {
    String customerId = AppSettings.customerId;
    final url = Uri.parse(
        "http://armintaaqua.com:3000/api/userAccounts/$customerId");

    try {
      final response = await http.get(url);
      if (response.statusCode != 200) return;

      final body = json.decode(response.body);
      final data = body["data"] ?? {};

      final List<TransactionModel> loaded = [];

      double parseAmount(dynamic v) {
        if (v == null) return 0;
        final s = v.toString().trim().toLowerCase();
        if (s.isEmpty || s == "null" || s == "undefined" || s == "nan") return 0;
        return double.tryParse(s) ?? 0;
      }

      String safe(dynamic v) {
        if (v == null) return "-";
        final s = v.toString().trim();
        if (s.isEmpty || s == "null" || s == "undefined") return "-";
        return s;
      }

      // ================= PAID =================
      for (final item in data["advance_paid_entries"] ?? []) {
        final amount = parseAmount(item["amount_paid"]);

        loaded.add(TransactionModel(
          safe(item["supplierName"]),
          safe(item["dateOfOrder"]),
          "+₹${amount.toStringAsFixed(0)}",
          Colors.green,
        ));
      }

      // ================= DELIVERED =================
      for (final item in data["delivered_entries"] ?? []) {
        final amount = parseAmount(item["amount"]);

        loaded.add(TransactionModel(
          safe(item["supplierName"]),
          safe(item["date"] ?? item["dateOfOrder"]),
          "+₹${amount.toStringAsFixed(0)}",
          Colors.blue,
        ));
      }

      // ================= PENDING =================
      for (final item in data["pending_entries"] ?? []) {
        final amount = parseAmount(item["amount"]);

        loaded.add(TransactionModel(
          safe(item["supplierName"]),
          safe(item["date"]),
          "₹${amount.toStringAsFixed(0)}",
          Colors.orange,
        ));
      }

      // ================= REJECTED =================
      for (final item in data["rejected_entries"] ?? []) {
        final amount = parseAmount(item["amount"]);

        loaded.add(TransactionModel(
          safe(item["supplierName"]),
          safe(item["date"]),
          "₹${amount.toStringAsFixed(0)}",
          Colors.grey,
        ));
      }

      setState(() {
        transactions = loaded; // ← ALL RECORDS NOW
        isLoading = false;
      });
    } catch (e) {
      isLoading = false;
      debugPrint("Transactions error: $e");
    }
  }

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

  Widget _quickMenuItem(String imagePath, String title) {
    return Container(
      padding: EdgeInsets.all(12),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: Color(0XFFC3C4C4), width: 1.0),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Image.asset(imagePath, width: 20, height: 20, fit: BoxFit.contain),
          SizedBox(height: 8),
          Text(
            title,
            style: fontTextStyle(14, Color(0xFF2A2A2A), FontWeight.w600),
          ),
        ],
      ),
    );
  }

  Widget _transferItem(String name, String imagePath) {
    return Column(
      children: [
        Container(
          width: 56,
          height: 56,
          decoration: BoxDecoration(
            color: Color(0xFFE8F2FF),
            borderRadius: BorderRadius.circular(28), // 28px radius = circle
          ),
          child: ClipRRect(
            borderRadius: BorderRadius.circular(28),
            child: Image.asset(
              imagePath,
              width: 56,
              height: 56,
            ),
          ),
        ),
        SizedBox(height: 4),
        Text(name, style: TextStyle(fontSize: 12)),
      ],
    );
  }

  Widget _transactionItem(
      String supplier, String dateTime, String amount, Color color) {
    return ListTile(
      contentPadding: EdgeInsets.zero, // 👈 removes default padding
      title: Text(
        supplier,
        style: TextStyle(fontWeight: FontWeight.w600),
      ),
      subtitle: Text(dateTime),
      trailing: Text(
        amount,
        style: TextStyle(color: color, fontWeight: FontWeight.w600),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor:  Colors.white,
      body: SingleChildScrollView(
        padding: EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // Quick Menu
            Text(
              "Quick Menu",
              style: fontTextStyle(14, Color(0xFF2A2A2A), FontWeight.w600),
            ),
            SizedBox(height: 12),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [



                Expanded(
                  child: GestureDetector(
                    onTap: (){
                      Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (context) => CreditAccountsScreen()),
                      );
                    },
                    child: _quickMenuItem('images/credit-accounts.png', "Credit Accounts"),
                  ),
                ),
                SizedBox(width: 12), // spacing between items
                Expanded(
                  child: _quickMenuItem('images/payment-methods.png', "Payment methods"),
                ),
                SizedBox(width: 12),
                Expanded(
                  child: _quickMenuItem('images/spending-summary.png', "Spending\nSummary"),
                ),
              ],
            ),
            SizedBox(height: 20),
            // Payment due card
            Container(
              padding: EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: Color(0xFF1D7AFC),
                borderRadius: BorderRadius.circular(12),
              ),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Container(
                          width: 32,
                          height: 32,
                          decoration: BoxDecoration(
                            shape: BoxShape.circle,
                            color: Color(0xFF1968D6),
                          ),
                          child: Center(
                            child: Image.asset(
                              'images/truck-payments.png',
                              width: 20,
                              height: 20,
                            ),
                          ),
                        ),
                        SizedBox(height: 8),
                        Text(
                          "Payment due",
                          style:
                          fontTextStyle(12, Color(0xFFFFFFFF), FontWeight.w500),
                        ),
                        SizedBox(height: 4),
                        Text(
                          "Due today, May 20, 2025",
                          style:
                          fontTextStyle(10, Color(0xFFFFFFFF), FontWeight.w400),
                        ),
                      ],
                    ),
                  ),
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.end,
                    children: [
                      Text(
                        "₹2,864.10",
                        style:
                        fontTextStyle(16, Color(0xFFFFFFFF), FontWeight.w500),
                      ),
                      SizedBox(height: 30),
                      Container(
                        padding:
                        EdgeInsets.symmetric(horizontal: 12, vertical: 4),
                        decoration: BoxDecoration(
                          color: Color(0xFF36AF31),
                          borderRadius: BorderRadius.circular(12),
                        ),
                        child: Text(
                          "Pay now",
                          style:
                          fontTextStyle(10, Color(0xFFFFFFFF), FontWeight.w600),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
            SizedBox(height: 20),
            // Transfer
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  "Transfer",
                  style: fontTextStyle(14, Color(0xFF2A2A2A), FontWeight.w600),
                ),
                Image.asset('images/arrow-right.png', width: 16, height: 16),
              ],
            ),
            SizedBox(height: 12),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                Column(
                  children: [
                    DottedBorder(
                      borderType: BorderType.Circle,
                      dashPattern: [6, 3],
                      color: Colors.grey,
                      strokeWidth: 1,
                      child: Container(
                        width: 48,
                        height: 48,
                        alignment: Alignment.center,
                        child: Icon(Icons.add, color: Colors.black),
                      ),
                    ),
                    SizedBox(height: 4),
                    Text("Add", style: TextStyle(fontSize: 12)),
                  ],
                ),
                _transferItem("Name", 'images/profile_user.png'),
                _transferItem("Name", 'images/profile_user.png'),
                _transferItem("Name", 'images/profile_user.png'),
                _transferItem("Name", 'images/profile_user.png'),
              ],
            ),
            SizedBox(height: 20),
            // Transactions
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  "Transactions",
                  style: fontTextStyle(14, Color(0xFF2A2A2A), FontWeight.w600),
                ),
                GestureDetector(
                  onTap: (){
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) => Transactions(
                          transactions: transactions,
                        ),
                      ),
                    );
                  },
                  child: Image.asset(
                    'images/arrow-right.png', // Replace with your actual image path
                    width: 16,
                    height: 16,
                  ),
                )

              ],
            ),
            SizedBox(height: 12),

            // Transaction list
            isLoading
                ? const Center(child: CircularProgressIndicator(color: primaryColor,)):

            (transactions.length != 0
                ?   ListView.builder(
              physics: NeverScrollableScrollPhysics(),
              shrinkWrap: true,
              itemCount: transactions.length,
              itemBuilder: (context, index) {
                final txn = transactions[index];
                return _transactionItem(
                  txn.name,
                  txn.dateTime,
                  txn.amount,
                  txn.color,
                );
              },
            )
                : Center(
              child: Text(
                'No Data Available',
                style: fontTextStyle(12, Color(0XFF000000), FontWeight.w500),
              ),
            ))

          ],
        ),
      ),
    );
  }
}
