import 'package:flutter/material.dart';
import 'package:supplier_new/common/settings.dart';
import 'package:supplier_new/financials/add_transactions.dart';
import 'package:supplier_new/financials/building_transactions_details.dart';
import 'package:supplier_new/financials/create_credit_accounts.dart';


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

  @override
  State<FinancialMainScreen> createState() => _FinancialMainScreenState();
}

Color _amountColor(Map<String, dynamic> txn) {
  if ((txn["status"] ?? "").toString().toLowerCase() == "failed") {
    return const Color(0xFF9F9F9F); // gray
  }

  final amt = (txn["amount"] ?? "").toString().trim();
  if (amt.startsWith('+')) return const Color(0xFF0A9E04); // green
  if (amt.startsWith('-')) return const Color(0xFFE2483D); // red
  return const Color(0xFF2D2E30); // default/dark text
}
class _FinancialMainScreenState extends State<FinancialMainScreen>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;

  final transactions = [
    {
      "name": "My Home Bhooja",
      "date": "21 August",
      "amount": "+ ₹2,580",
      "color": Colors.green,
      "status": "success",
    },
    {
      "name": "Ramakrishna",
      "date": "20 August",
      "amount": "- ₹748",
      "color": Colors.red,
      "status": "success",
    },
    {
      "name": "Malleshan Water Supplies",
      "date": "21 August",
      "amount": "- ₹10,000",
      "color": Colors.red,
      "status": "success",
    },
    {
      "name": "My Home Bhooja",
      "date": "21 August",
      "amount": "+ ₹2,580",
      "color": Colors.grey,
      "status": "failed",
    },
    {
      "name": "My Home Bhooja",
      "date": "21 August",
      "amount": "+ ₹2,580",
      "color": Colors.green,
      "status": "success",
    },
  ];

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
    _tabController.addListener(() {
      setState(() {}); // rebuilds FAB visibility when tab changes
    });
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  Widget fab() {
    final index = _tabController.index;

    if (index == 0) {
      return SizedBox(
        width: 52,
        height: 52,
        child: FloatingActionButton(
          shape: const CircleBorder(),
          backgroundColor: Colors.black,
          onPressed: _onFabPressed,
          child: Image.asset(
            "images/plus.png",
            width: 20,
            height: 20,
            color: Colors.white,
          ),
        ),
      );
    } else {
      return Container();
    }
  }

  void _onFabPressed() {
    final index = _tabController.index;

    if (index == 0) {
      // Tab 1 → Navigate to Create Account
      Navigator.push(
        context,
        MaterialPageRoute(
          builder: (_) => AddTransactionScreen(),
        ),
      );
    } else if (index == 1) {
      // Tab 2 → Navigate to Transactions
      /*Navigator.push(
        context,
        MaterialPageRoute(builder: (_) => const TransactionsPage()),
      );*/
    }
  }


  Widget Transactions() {
    return Container(
      color: Color(0XFFFFFFFF),
      child: Column(
        children: [
          // Filters row
          SingleChildScrollView(
            scrollDirection: Axis.horizontal,
            padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
            child: Row(
              children: [
                _buildFilterChip("Status"),
                _buildFilterChip("Payment Method"),
                _buildFilterChip("Date"),
                _buildFilterChip("Amount"),
              ],
            ),
          ),

          Expanded(
            child: ListView.builder(
              padding: EdgeInsets.zero,
              itemCount: transactions.length,
              itemBuilder: (context, index) {
                final txn = transactions[index];

                return ListTile(
                  dense: true, //
                  minVerticalPadding: 0,
                  visualDensity: const VisualDensity(vertical: 0, horizontal: 0), // ✅ tighter
                  contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 0), // ✅ no extra top/bottom
                  horizontalTitleGap: 8,
                  minLeadingWidth: 40,
                  leading: const CircleAvatar(
                    radius: 18,
                    backgroundColor: Colors.blue,
                    child: Icon(Icons.person, color: Colors.white, size: 18),
                  ),
                  title: Text(
                    txn["name"].toString(),
                    style: fontTextStyle(14,  Color(0xFF2D2E30), FontWeight.w500)
                        .copyWith(height: 1.1), // ✅ tighter line height
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                  subtitle: Text(
                    txn["date"].toString(),
                    style: fontTextStyle(12,  Color(0xFF939495), FontWeight.w400)
                        .copyWith(height: 1.0), // ✅ tighter line height
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),

                  trailing: Column(
                    crossAxisAlignment: CrossAxisAlignment.end,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text(
                        txn["amount"].toString(),
                        style: fontTextStyle(12, _amountColor(txn), FontWeight.w600),
                      ),
                      if ((txn["status"] ?? "").toString().toLowerCase() == "failed")
                        Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            const Icon(Icons.error, color: Color(0xFF9F9F9F), size: 14), // gray
                            const SizedBox(width: 4),
                            Text(
                              "Failed",
                              style: fontTextStyle(10, const Color(0xFF9F9F9F), FontWeight.w400),
                            ),
                          ],
                        ),
                    ],
                  ),

                );
              },
            ),
          )

        ],
      ),
    );
  }

  Widget CreditAccounts() {
    return SingleChildScrollView(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          children: [
            // Account Summary

            Align(
              alignment: Alignment.centerRight, // aligns button to the right
              child: OutlinedButton(
                style: OutlinedButton.styleFrom(
                  foregroundColor: Color(0xFFFFFFFF),
                  backgroundColor: Color(0xFF000000),
                  side: BorderSide(color: Color(0xFF000000)),
                  padding: EdgeInsets.symmetric(
                      vertical: 10, horizontal: 16), // padding around content
                ),
                onPressed: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (_) => CreateCreditAccountScreen(),
                    ),
                  );
                },
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  // shrink button to fit content
                  children: [
                    Image.asset('images/plus.png', height: 20, width: 20),
                    SizedBox(width: 4),
                    Text(
                      "Create Account",
                      style: fontTextStyle(12, const Color(0xFFFFFFFF), FontWeight.w400),
                    ),
                  ],
                ),
              ),
            ),

            // Account Summary (ONLY header + count)
            Container(
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(16),
              ),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Expanded(
                    child: Text(
                      "Account Summary",
                      style: fontTextStyle(12, const Color(0xFF2D2E30), FontWeight.w500),
                    ),
                  ),
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.end,
                    children: [
                      Text(
                        "05",
                        style: fontTextStyle(24, const Color(0xFF0D3771), FontWeight.w500),
                      ),
                      const SizedBox(height: 2),
                      Text(
                        "4 active, 1 overdue",
                        style: fontTextStyle(10, const Color(0xFF646566), FontWeight.w400),
                      ),
                    ],
                  ),
                ],
              ),
            ),

            const SizedBox(height: 12),

// NEW: Balances in a separate container/card
            Container(
              padding: const EdgeInsets.all(16),

              child: Row(
                children: [
                  Expanded(
                    child: Container(
                      padding: const EdgeInsets.all(12),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(12),
                        color: const Color(0xffFFFFFF),
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text("Receivable Balance",
                              style: fontTextStyle(12,  Color(0xFF2D2E30), FontWeight.w500)),
                          const SizedBox(height: 4),
                          Text("₹24,000",
                              style: fontTextStyle(16, Color(0xFFE2483D), FontWeight.w500)),
                          Text("40.6% of total credit",
                              style: fontTextStyle(10,  Color(0xFF646566), FontWeight.w400)),
                        ],
                      ),
                    ),
                  ),
                  const SizedBox(width: 12),
                  Expanded(
                    child: Container(
                      padding: const EdgeInsets.all(12),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(12),
                        color: const Color(0xffFFFFFF),
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text("Advance Balance",
                              style: fontTextStyle(12,  Color(0xFF2D2E30), FontWeight.w500)),
                          const SizedBox(height: 4),
                          Text("₹24,000",
                              style: fontTextStyle(16, Color(0xFFE2483D), FontWeight.w500)),
                          Text("60.4% of total credit",
                              style: fontTextStyle(10,  Color(0xFF646566), FontWeight.w400)),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),

            const SizedBox(height: 20),

            // Search Bar
            Container(
              padding:
              const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(12),
              ),
              child: Row(
                children: [
                  const Icon(Icons.search, color: Colors.grey),
                  const SizedBox(width: 8),
                  const Expanded(
                    child: TextField(
                      decoration: InputDecoration(
                        hintText: "Search",
                        border: InputBorder.none,
                      ),
                    ),
                  ),
                  Image.asset("images/icon_tune.png", width: 24, height: 24),
                  const SizedBox(width: 16),
                  Image.asset("images/up_down_arrow.png", width: 24, height: 24),
                ],
              ),
            ),

            const SizedBox(height: 20),

            // Accounts List
            _accountTile(
              name: "SVG Towers",
              status: "active",
              orders: "48 orders",
              balance: "₹10,000",
              credit: "₹10,000",
              lastPayment: "₹5,000 | 12 Aug",
              balanceColor: Colors.red,
              creditColor: Colors.green,
            ),
            _accountTile(
              name: "Canvas Creations",
              status: "active",
              orders: "32 orders",
              balance: "₹7,500",
              credit: "₹7,500",
              lastPayment: "₹3,000 | 5 Aug",
              balanceColor: Colors.red,
              creditColor: Colors.green,
            ),
            _accountTile(
              name: "Digital Designs",
              status: "inactive",
              orders: "15 orders",
              balance: "₹2,000",
              credit: "₹2,000",
              lastPayment: "₹1,000 | 1 Aug",
              balanceColor: Colors.red,
              creditColor: Colors.green,
            ),
          ],
        ),
      ),
    );
  }

  Widget _accountTile({
    required String name,
    required String status,
    required String orders,
    required String balance,
    required String credit,
    required String lastPayment,
    required Color balanceColor,
    required Color creditColor,
  }) {
    return GestureDetector(
      onTap: () {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (_) => BuildingTransactionsDetails(),
          ),
        );
      },
      child: Container(
        margin: const EdgeInsets.only(bottom: 12),
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(16),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // Name + Status
            Row( children: [ Expanded( child: Text( name, style: fontTextStyle(14, Color(0xFF2D2E30), FontWeight.w500)), ), Container( padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), decoration: BoxDecoration( color: status == "active" ? Colors.green.withOpacity(0.1) : Colors.red.withOpacity(0.1), borderRadius: BorderRadius.circular(12), ), child: Text( status, style: TextStyle( color: status == "active" ? Colors.green : Colors.redAccent, fontSize: 12, fontWeight: FontWeight.w500, ), ), ) ], ),
            const SizedBox(height: 4),
            Text(
              orders,
              style: const TextStyle(color: Colors.grey, fontSize: 12),
            ),
            const SizedBox(height: 12),

            // Balance - Credit - Last Payment
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text("Available Balance",
                        style: TextStyle(fontSize: 12, color: Colors.black54)),
                    const SizedBox(height: 4),
                    Text(
                      balance,
                      style: TextStyle(fontSize: 14,
                          fontWeight: FontWeight.bold,
                          color: balanceColor),
                    ),
                  ],
                ),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text("Available Credit",
                        style: TextStyle(
                            fontSize: 12, color: Colors.black54)),
                    const SizedBox(height: 4),
                    Text(
                      credit,
                      style: TextStyle(fontSize: 14,
                          fontWeight: FontWeight.bold,
                          color: creditColor),
                    ),
                  ],
                ),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text("Last Payment",
                        style: TextStyle(fontSize: 12, color: Colors.black54)),
                    const SizedBox(height: 4),
                    Text(
                      lastPayment,
                      style: fontTextStyle(
                          12, Color(0XFFF1F1F1), FontWeight.w500),
                    ),
                  ],
                ),
              ],
            )
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        elevation: 0,
        backgroundColor: Colors.white,
        bottom: PreferredSize(
          preferredSize: const Size.fromHeight(0.0),
          child: Container(
            height: 38,
            margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
            child: AnimatedBuilder(
              animation: _tabController,
              builder: (context, _) {
                return TabBar(
                  controller: _tabController,
                  indicatorColor: Colors.transparent,
                  // remove underline
                  dividerColor: Colors.transparent,
                  isScrollable: false,
                  overlayColor: MaterialStateProperty.all(Colors.transparent),
                  // equal width
                  tabs: List.generate(2, (index) {
                    final labels = ['Transactions', 'Credit Accounts'];
                    final isSelected = _tabController.index == index;

                    return Container(
                      decoration: BoxDecoration(
                        color: isSelected ? const Color(0XFFF1F1F1) : Colors
                            .transparent,
                        borderRadius: BorderRadius.circular(27),
                      ),
                      alignment: Alignment.center,
                      child: Text(
                        labels[index],
                        style: fontTextStyle(
                          12, Color(0XFF000000), FontWeight.w600,
                        ),
                      ),
                    );
                  }),
                );
              },
            ),
          ),
        ),
      ),
      body: TabBarView(
        controller: _tabController,
        children: [
          // Tab 1: Transactions
          Transactions(),

          // Tab 2: Credit Accounts
          CreditAccounts()
        ],
      ),


      floatingActionButton: _tabController.index == 0 ? fab() : null,
    );
  }

  Widget _buildFilterChip(String text) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 4),
      child: FilterChip(
        label: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(
              text,
              style: const TextStyle(
                fontSize: 12,
                fontWeight: FontWeight.w500,
                color: Colors.black,
              ),
            ),
            const SizedBox(width: 4),
            const Icon(
              Icons.keyboard_arrow_down, // ⬇️ Down arrow
              size: 18,
              color: Colors.black,
            ),
          ],
        ),
        backgroundColor: Colors.white,
        selectedColor: const Color(0XFFF1F1F1),
        side: const BorderSide(color: Color(0XFF444444)),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(16),
        ),
        onSelected: (val) {
        },
      ),
    );
  }

}