import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import '../database_helper.dart';

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

  @override
  _TransactionSummaryBySiteScreenState createState() =>
      _TransactionSummaryBySiteScreenState();
}

class _TransactionSummaryBySiteScreenState
    extends State<TransactionSummaryBySiteScreen> {
  List<Map<String, dynamic>> sites = [];
  int? selectedSiteId;
  Map<String, dynamic>? summary;
  bool isLoadingSites = true;
  bool isLoadingSummary = false;

  List<Map<String, dynamic>> previousTransactions = [];
  bool isLoadingTransactions = false;

  DateTime? startDate;
  DateTime? endDate;

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

  Future<void> _loadSites() async {
    final siteList = await DatabaseHelper.instance.getSites();
    setState(() {
      sites = [
        {'id': -1, 'name': 'All Sites'},
        ...siteList
      ];
      isLoadingSites = false;
      if (sites.isNotEmpty) {
        selectedSiteId = sites.first['id'];
        _loadSummaryForSite(selectedSiteId!);
      }
    });
  }

  Future<void> _loadSummaryForSite(int siteId) async {
    setState(() {
      isLoadingSummary = true;
      isLoadingTransactions = true;
      summary = null;
      previousTransactions = [];
    });

    late final Map<String, dynamic> data;
    late final List<Map<String, dynamic>> transactions;

    if (siteId == -1) {
      data = await DatabaseHelper.instance
          .getMonthlyTransactionSummaryAllSites(startDate, endDate);
      transactions = await DatabaseHelper.instance
          .getAllTransactionsFiltered(startDate, endDate);
    } else {
      data = await DatabaseHelper.instance
          .getFullTransactionSummaryBySite(siteId, startDate, endDate);
      transactions = await DatabaseHelper.instance
          .getTransactionsBySiteFiltered(siteId, startDate, endDate);
    }

    setState(() {
      summary = data;
      previousTransactions = transactions;
      isLoadingSummary = false;
      isLoadingTransactions = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    if (isLoadingSites) {
      return const Center(child: CircularProgressIndicator());
    }

    return Scaffold(
      backgroundColor: const Color(0xFFF1F8E9),
      appBar: AppBar(
        backgroundColor: Colors.teal,
        title: const Text('Transaction Report'),
      ),
      body: SafeArea(
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const Text("Select Site",
                  style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600)),
              const SizedBox(height: 8),
              DropdownButtonFormField<int>(
                value: selectedSiteId,
                decoration: InputDecoration(
                  filled: true,
                  fillColor: Colors.white,
                  contentPadding:
                      const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
                  border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(10)),
                ),
                isExpanded: true,
                items: sites.map((site) {
                  return DropdownMenuItem<int>(
                    value: site['id'],
                    child: Text(site['name']),
                  );
                }).toList(),
                onChanged: (value) {
                  if (value != null) {
                    setState(() {
                      selectedSiteId = value;
                    });
                    _loadSummaryForSite(value);
                  }
                },
              ),
              const SizedBox(height: 16),
              Row(
                children: [
                  Expanded(
                    child: ElevatedButton.icon(
                      icon: const Icon(Icons.date_range),
                      label: Text(
                        startDate == null || endDate == null
                            ? 'Select Date Range'
                            : '${DateFormat('dd MMM').format(startDate!)} - ${DateFormat('dd MMM').format(endDate!)}',
                      ),
                      onPressed: () async {
                        final picked = await showDateRangePicker(
                          context: context,
                          firstDate: DateTime(2000),
                          lastDate: DateTime.now(),
                          initialDateRange: startDate != null && endDate != null
                              ? DateTimeRange(start: startDate!, end: endDate!)
                              : null,
                        );

                        if (picked != null) {
                          setState(() {
                            startDate = picked.start;
                            endDate = picked.end;
                          });
                          _loadSummaryForSite(selectedSiteId!);
                        }
                      },
                    ),
                  ),
                  const SizedBox(width: 8),
                  if (startDate != null || endDate != null)
                    IconButton(
                      icon: const Icon(Icons.clear),
                      onPressed: () {
                        setState(() {
                          startDate = null;
                          endDate = null;
                        });
                        _loadSummaryForSite(selectedSiteId!);
                      },
                    ),
                ],
              ),
              const SizedBox(height: 24),
              if (isLoadingSummary)
                const Center(child: CircularProgressIndicator())
              else if (summary == null)
                const Center(child: Text("No data available."))
              else
                Card(
                  elevation: 4,
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(12)),
                  color: Colors.white,
                  child: Padding(
                    padding: const EdgeInsets.all(16),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          "Site: ${sites.firstWhere((s) => s['id'] == selectedSiteId, orElse: () => {
                                'name': 'Unknown'
                              })['name']}",
                          style: const TextStyle(
                              fontWeight: FontWeight.bold,
                              fontSize: 18,
                              color: Colors.black87),
                        ),
                        const SizedBox(height: 12),
                        _buildRow("Total Income:", summary!['totalIncome'],
                            color: Colors.green),
                        _buildRow("Total Expense:", summary!['totalExpense'],
                            color: Colors.red),
                        const Divider(),
                        _buildRow("Net Total:", summary!['netTotal'],
                            color: Colors.blue),
                      ],
                    ),
                  ),
                ),
              const SizedBox(height: 16),
              if (selectedSiteId != null)
                Expanded(
                  child: FutureBuilder<List<Map<String, dynamic>>>(
                    future: DatabaseHelper.instance
                        .getTransactionsBySiteFiltered(
                            selectedSiteId!, startDate, endDate),
                    builder: (context, snapshot) {
                      if (!snapshot.hasData) {
                        return const CircularProgressIndicator();
                      }

                      final transactions = snapshot.data!;
                      if (transactions.isEmpty) {
                        return const Text("No previous transactions found.");
                      }

                      return ListView(
                        children: transactions.map((tx) {
                          final isIncome = tx['type'] == 'income';
                          final sign = isIncome ? '+' : '-';
                          final amount = tx['amount'];

                          return ListTile(
                            title: Text(
                              "${tx['type'].toString().toUpperCase()}  $sign ₹$amount",
                              style:
                                  const TextStyle(fontWeight: FontWeight.bold),
                            ),
                            subtitle: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(
                                  'Date: ${DateFormat('yyyy-MM-dd').format(DateTime.parse(tx['date']))}',
                                  style: const TextStyle(
                                      fontSize: 14, color: Colors.grey),
                                ),
                                if (tx['note'] != null &&
                                    tx['note'].toString().trim().isNotEmpty)
                                  Text(
                                    'Note: ${tx['note']}',
                                    style: const TextStyle(
                                        fontSize: 14, color: Colors.black87),
                                  ),
                                Text("Pond: ${tx['pond_name'] ?? 'N/A'}"),
                              ],
                            ),
                          );
                        }).toList(),
                      );
                    },
                  ),
                ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildRow(String label, dynamic value, {Color color = Colors.black}) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 6),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(label, style: const TextStyle(fontSize: 16)),
          Text(
            value is double ? value.toStringAsFixed(2) : value.toString(),
            style: TextStyle(
                fontSize: 16, fontWeight: FontWeight.w600, color: color),
          ),
        ],
      ),
    );
  }
}