import 'package:flutter/material.dart';
import 'package:my_attendance/services/attendance_service.dart';
import 'package:provider/provider.dart';

class StatsDialog extends StatelessWidget {
  const StatsDialog({super.key});

  @override
  Widget build(BuildContext context) {
    final attendanceService = Provider.of<AttendanceService>(
      context,
      listen: false,
    );
    final monthlyStats = attendanceService.monthlyStats;
    final yearlyStats = attendanceService.yearlyStats;

    return AlertDialog(
      title: const Text('Attendance Summary'),
      content: SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisSize: MainAxisSize.min,
          children: [
            _buildStatsSection(context, 'This Month', monthlyStats),
            const SizedBox(height: 24),
            _buildStatsSection(context, 'This Year', yearlyStats),
          ],
        ),
      ),
      actions: [
        TextButton(
          onPressed: () => Navigator.of(context).pop(),
          child: const Text('Close'),
        ),
      ],
    );
  }

  Widget _buildStatsSection(
    BuildContext context,
    String title,
    Map<String, int> stats,
  ) {
    if (stats.isEmpty) {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(title, style: Theme.of(context).textTheme.titleLarge),
          const Padding(
            padding: EdgeInsets.symmetric(vertical: 16.0),
            child: Text('No entries found.'),
          ),
        ],
      );
    }

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(title, style: Theme.of(context).textTheme.titleLarge),
        const Divider(),
        ...stats.entries.map(
          (entry) => ListTile(
            title: Text(entry.key),
            trailing: Text(
              entry.value.toString(),
              style: Theme.of(
                context,
              ).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold),
            ),
          ),
        ),
      ],
    );
  }
}
