import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:supplier_new/common/settings.dart';
import 'package:supplier_new/financials/add_transaction_for_credit_account.dart';

class BuildingTransactionsDetails extends StatefulWidget {
  final String supplierId;
  final String customerId;

  const BuildingTransactionsDetails({
    super.key,
    required this.supplierId,
    required this.customerId,
  });

  @override
  State<BuildingTransactionsDetails> createState() =>
      _BuildingTransactionsDetailsState();
}

class _BuildingTransactionsDetailsState
    extends State<BuildingTransactionsDetails> {
  bool isLoading = true;

  List<Map<String, dynamic>> transactions = [];

  double advanceBalance = 0;
  double receivableBalance = 0;

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

  // ========================= API =========================
  Future<void> fetchTransactions() async {
    try {
      final response =
      await AppSettings.getAdvanceTransactionsBySupplierAndCustomer(
        widget.supplierId,
        widget.customerId,
      );

      final decoded = jsonDecode(response);
      final List list = decoded["data"] ?? [];

      double advance = 0;
      double receivable = 0;

      final txns = list.map<Map<String, dynamic>>((e) {
        final amount =
            double.tryParse(e["advance_amount"].toString()) ?? 0;

        if (amount >= 0) {
          advance += amount;
        } else {
          receivable += amount.abs();
        }

        return {
          "title": e["payment_type"] ?? "Transaction",
          "date": e["date_of_transaction"] ?? "",
          "amount": amount,
          "isCredit": amount >= 0,
        };
      }).toList();

      setState(() {
        transactions = txns;
        advanceBalance = advance;
        receivableBalance = receivable;
        isLoading = false;
      });
    } catch (e) {
      debugPrint("❌ Transaction fetch error: $e");
      setState(() => isLoading = false);
    }
  }

  // ========================= UI =========================
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppSettings.supplierAppBarWithActionsText(widget.customerId, context),
      floatingActionButton: SizedBox(
        width: 52,
        height: 52,
        child: FloatingActionButton(
          shape: const CircleBorder(),
          backgroundColor: Colors.black,
          onPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (_) => AddCreditTransactionPage(),
              ),
            );
          },
          child: Image.asset(
            "images/plus.png",
            width: 20,
            height: 20,
            color: Colors.white,
          ),
        ),
      ),
      body: SafeArea(
        child: Column(
          children: [

            // ================= STATEMENT =================
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  OutlinedButton.icon(
                    onPressed: () {},
                    icon: const Icon(Icons.download),
                    label: const Text("Statement"),
                  ),
                ],
              ),
            ),

            // ================= BALANCES =================
            Padding(
              padding: const EdgeInsets.all(16),
              child: Container(
                padding: const EdgeInsets.all(16),
                decoration: BoxDecoration(
                  color: Colors.grey.shade100,
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Column(
                  children: [
                    Row(
                      children: [
                        Expanded(
                          child: _balanceBox(
                            title: "Receivable Balance",
                            amount: receivableBalance,
                            color: Colors.red,
                          ),
                        ),
                        const SizedBox(width: 12),
                        Expanded(
                          child: _balanceBox(
                            title: "Advance Balance",
                            amount: advanceBalance,
                            color: Colors.green,
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),

            // ================= ACTION BUTTONS =================
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16),
              child: Row(
                children: [
                  Expanded(
                    child: ElevatedButton(
                      onPressed: () {},
                      child: const Text("Add Transaction"),
                    ),
                  ),
                  const SizedBox(width: 12),
                  Expanded(
                    child: OutlinedButton(
                      onPressed: () {},
                      child: const Text("Request Top up"),
                    ),
                  ),
                ],
              ),
            ),

            const SizedBox(height: 12),

            // ================= HISTORY =================
            const Padding(
              padding: EdgeInsets.symmetric(horizontal: 16),
              child: Align(
                alignment: Alignment.centerLeft,
                child: Text(
                  "HISTORY",
                  style: TextStyle(fontWeight: FontWeight.w600),
                ),
              ),
            ),

            const SizedBox(height: 8),

            Expanded(
              child: isLoading
                  ? const Center(child: CircularProgressIndicator())
                  : ListView.builder(
                padding:
                const EdgeInsets.symmetric(horizontal: 16),
                itemCount: transactions.length,
                itemBuilder: (context, index) {
                  final txn = transactions[index];
                  return _historyItem(
                    txn["title"],
                    txn["date"],
                    "₹${txn["amount"].abs()}",
                    txn["isCredit"],
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  // ================= HELPERS =================
  Widget _balanceBox({
    required String title,
    required double amount,
    required Color color,
  }) {
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(title),
          const SizedBox(height: 4),
          Text(
            "₹${amount.toStringAsFixed(0)}",
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
              color: color,
            ),
          ),
        ],
      ),
    );
  }

  Widget _historyItem(
      String title, String date, String amount, bool isCredit) {
    return ListTile(
      contentPadding: EdgeInsets.zero,
      leading: CircleAvatar(
        backgroundColor: Colors.blue.shade100,
        child: const Icon(Icons.swap_horiz, color: Colors.blue),
      ),
      title: Text(title),
      subtitle: Text(date),
      trailing: Text(
        amount,
        style: TextStyle(
          fontWeight: FontWeight.bold,
          color: isCredit ? Colors.green : Colors.red,
        ),
      ),
    );
  }
}
