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

import 'Daily_Transaction_List_Page.dart';

class DailySummaryPage extends StatefulWidget {
  const DailySummaryPage({Key? key}) : super(key: key);

  @override
  State<DailySummaryPage> createState() => _DailySummaryPageState();
}

class _DailySummaryPageState extends State<DailySummaryPage> {
  DateTime? _selectedDate;
  bool _loading = false;

  int _pendingTotal = 0;
  int _confirmedTotal = 0;
  int _rejectedTotal = 0;

  int _pendingCount = 0;
  int _confirmedCount = 0;
  int _rejectedCount = 0;

  @override
  void initState() {
    super.initState();
    _selectedDate = DateTime.now();
    _fetchDataForDate(_selectedDate!);
  }

  Future<void> _selectDate() async {
    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: _selectedDate ?? DateTime.now(),
      firstDate: DateTime(2025),
      lastDate: DateTime(2040),
    );
    if (picked != null && picked != _selectedDate) {
      setState(() {
        _selectedDate = picked;
      });
      _fetchDataForDate(picked);
    }
  }

  Future<void> _fetchDataForDate(DateTime date) async {
    setState(() {
      _loading = true;
      _pendingTotal = 0;
      _confirmedTotal = 0;
      _rejectedTotal = 0;

      _pendingCount = 0;
      _confirmedCount = 0;
      _rejectedCount = 0;
    });

    try {
      QuerySnapshot snapshot = await FirebaseFirestore.instance
          .collection('payments')
          .where('timestamp',
          isGreaterThanOrEqualTo: DateTime(date.year, date.month, date.day))
          .where('timestamp',
          isLessThanOrEqualTo:
          DateTime(date.year, date.month, date.day, 23, 59, 59))
          .get();

      for (var doc in snapshot.docs) {
        final data = doc.data() as Map<String, dynamic>;
        final amountData = data['totalAmount'];
        int amount;

        if (amountData is int) {
          amount = amountData;
        } else if (amountData is double) {
          amount = amountData.toInt(); // ✅ Double কে Int-এ কনভার্ট
        } else if (amountData is String) {
          amount = int.tryParse(amountData) ?? 0;
        } else {
          amount = 0;
        }

        final String status = data['status'] ?? 'Pending';


        if (status == 'Pending') {
          _pendingTotal += amount;
          _pendingCount++;
        } else if (status == 'Confirmed') {
          _confirmedTotal += amount;
          _confirmedCount++;
        } else if (status == 'Rejected') {
          _rejectedTotal += amount;
          _rejectedCount++;
        }
      }
    } catch (e) {
      print('Error fetching data: $e');
    }

    setState(() {
      _loading = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    String formattedDate = _selectedDate != null
        ? DateFormat('dd-MM-yyyy').format(_selectedDate!)
        : 'তারিখ নির্বাচন করুন';

    return Scaffold(
      appBar: AppBar(
        title: const Text('দৈনিক পেমেন্ট সারসংক্ষেপ'),
      ),
      body: _loading
          ? const Center(child: CircularProgressIndicator())
          : Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          children: [
            ElevatedButton.icon(
              onPressed: _selectDate,
              icon: const Icon(Icons.date_range),
              label: Text(formattedDate),
            ),
            const SizedBox(height: 20),


            InkWell(
              onTap: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => DailyTransactionListPage(
                      date: _selectedDate!,
                      status: 'Pending',
                    ),
                  ),
                );
              },
              child: Card(
                color: Colors.orange[50],
                child: ListTile(
                  leading: const Icon(Icons.pending_actions, color: Colors.orange),
                  title: const Text('Pending Total'),
                  subtitle: Text('টোটাল ট্রানজেকশন: $_pendingCount'),
                  trailing: Text('৳$_pendingTotal', style: const TextStyle(fontWeight: FontWeight.bold)),
                ),
              ),
            ),

            const SizedBox(height: 10),


            InkWell(
              onTap: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => DailyTransactionListPage(
                      date: _selectedDate!,
                      status: 'Confirmed',
                    ),
                  ),
                );
              },
              child: Card(
                color: Colors.green[50],
                child: ListTile(
                  leading: const Icon(Icons.check_circle, color: Colors.green),
                  title: const Text('Confirmed Total'),
                  subtitle: Text('টোটাল ট্রানজেকশন: $_confirmedCount'),
                  trailing: Text('৳$_confirmedTotal', style: const TextStyle(fontWeight: FontWeight.bold)),
                ),
              ),
            ),

            const SizedBox(height: 10),


            InkWell(
              onTap: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => DailyTransactionListPage(
                      date: _selectedDate!,
                      status: 'Rejected',
                    ),
                  ),
                );
              },
              child: Card(
                color: Colors.red[50],
                child: ListTile(
                  leading: const Icon(Icons.cancel, color: Colors.red),
                  title: const Text('Rejected Total'),
                  subtitle: Text('টোটাল ট্রানজেকশন: $_rejectedCount'),
                  trailing: Text('৳$_rejectedTotal', style: const TextStyle(fontWeight: FontWeight.bold)),
                ),
              ),
            ),

          ],
        ),
      ),
    );
  }
}

এর ডিজাইন সুন্দর করুন, আকর্ষণীয় করুন