import 'package:flutter/material.dart';
import 'google_sheets_api.dart';

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

  @override
  State<SheetViewPage> createState() => _SheetViewPageState();
}

class _SheetViewPageState extends State<SheetViewPage> {
  final GoogleSheetsApi _api = GoogleSheetsApi();
  List<List<dynamic>> _rows = [];
  bool _loading = false;
  final Color _primaryColor = const Color(0xFF4361EE);
  String _query = '';

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

  Future<void> _load() async {
    setState(() => _loading = true);
    final data = await _api.readData();
    print('Données chargées : $data');
    setState(() {
      _rows = data ?? [];
      _loading = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF6F8FA),
      appBar: AppBar(
        title: const Text('Liste des Étudiants'),
        elevation: 1,
        actions: [
          IconButton(onPressed: _load, icon: const Icon(Icons.refresh_rounded)),
        ],
      ),
      body: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          children: [
            Card(
              elevation: 2,
              shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
              child: Padding(
                padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                child: Row(
                  children: [
                    Expanded(
                      child: TextField(
                        decoration: const InputDecoration(prefixIcon: Icon(Icons.search), hintText: 'Rechercher (nom, n° ou MAC)'),
                        onChanged: (v) => setState(() => _query = v.trim().toLowerCase()),
                      ),
                    ),
                    const SizedBox(width: 12),
                    Chip(label: Text('${_rows.length}')), 
                  ],
                ),
              ),
            ),

            const SizedBox(height: 12),

            Expanded(
              child: _loading
                  ? const Center(child: CircularProgressIndicator())
                  : _rows.isEmpty
                      ? Center(
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Icon(Icons.table_chart_outlined, size: 80, color: Colors.grey.shade300),
                              const SizedBox(height: 12),
                              Text('Aucune donnée', style: TextStyle(color: Colors.grey.shade600)),
                            ],
                          ),
                        )
                      : Card(
                          elevation: 2,
                          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
                          child: ListView.separated(
                            itemCount: _rows.length,
                            separatorBuilder: (c, i) => Divider(height: 1, color: Colors.grey.shade100),
                            itemBuilder: (context, index) {
                              final row = _rows[index];
                              final display = '${row.length > 1 ? '${row[1]} ${row[2]}' : 'Étudiant ${index + 1}'}';
                              final subtitle = row.isNotEmpty ? 'N°: ${row[0] ?? 'N/A'} • MAC: ${row.length > 3 ? row[3] ?? '-' : '-'}' : '';

                              // simple filter by query
                              if (_query.isNotEmpty) {
                                final combined = (row.join(' ')).toLowerCase();
                                if (!combined.contains(_query)) return const SizedBox.shrink();
                              }

                              return ListTile(
                                leading: CircleAvatar(backgroundColor: _primaryColor.withOpacity(0.12), child: Icon(Icons.person, color: _primaryColor)),
                                title: Text(display, style: const TextStyle(fontWeight: FontWeight.w600)),
                                subtitle: Text(subtitle, style: TextStyle(color: Colors.grey.shade600)),
                                trailing: const Icon(Icons.chevron_right_rounded, color: Colors.grey),
                                onTap: () => showDialog(
                                  context: context,
                                  builder: (_) => AlertDialog(
                                    title: Text(display),
                                    content: SingleChildScrollView(
                                      child: Column(
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        children: row.asMap().entries.map((entry) => Padding(
                                              padding: const EdgeInsets.symmetric(vertical: 4),
                                              child: Text('${_getColumnName(entry.key)}: ${entry.value ?? 'N/A'}'),
                                            )).toList(),
                                      ),
                                    ),
                                    actions: [TextButton(onPressed: () => Navigator.of(context).pop(), child: const Text('Fermer'))],
                                  ),
                                ),
                              );
                            },
                          ),
                        ),
            ),
          ],
        ),
      ),
    );
  }

  String _getColumnName(int index) {
    const columns = [
      'Numéro étudiant',
      'Prénom',
      'Nom',
      'MAC',
      'NFC',
      'QR Code',
      'Date d\'inscription'
    ];
    return index < columns.length ? columns[index] : 'Colonne $index';
  }
}