import 'package:flutter/material.dart';
import 'package:nfc_google_sheet/context/colories.dart';
import 'package:nfc_google_sheet/database/databaseHelper.dart';
import 'package:nfc_google_sheet/model/student.dart';

class SheetPage extends StatelessWidget {
  const SheetPage({super.key});
  static String? selectedFiliere;
  static String? selectedMatiere;

  @override
  Widget build(BuildContext context) {
    return MySheetPage();
  }
}

class MySheetPage extends StatefulWidget {
  const MySheetPage({super.key});
  @override
  State<MySheetPage> createState() => _MySheetPageState();
}

class _MySheetPageState extends State<MySheetPage> {
  late Future<List<Student>> _students;

  @override
  void initState() {
    super.initState();
    _students = _getStudents();
  }

  Future<List<Student>> _getStudents() async {
    final List<Map<String, dynamic>> maps = await DatabaseHelper.instance.queryAllUsers();
    return List.generate(maps.length, (i) {
      return Student.fromMap(maps[i]);
    });
  }

  void _showWarningMatiereUnselected(){
    showDialog(context: context, builder: (BuildContext context) {
      return AlertDialog(
        backgroundColor: Colories.background,
        title: Text("WARNING !", style: TextStyle(color: Colories.warning)),
        content: Text("Vous n'avez pas sélectionnez de matière dans l'application. Continuez quand même ?"),
        actions: [
          TextButton(
            child: Text("Non", style: TextStyle(color: Colories.unselected)),
            onPressed: () {
              // TODO: On annule tout
            },
          ),
          ElevatedButton(
            style: ElevatedButton.styleFrom(backgroundColor: Colories.selected),
            child: Text("Oui", style: TextStyle(color: Colories.background)),
            onPressed: () {
              Navigator.of(context).pop();
              _exportData(true);
            },
          ),
        ],
      );
    });
  }
  void _showExportDialog() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          backgroundColor: Colories.background,
          title: Text("Exporter les données", style: TextStyle(color: Colories.selected)),
          content: Text("Voulez-vous inclure la colonne 'ID Carte' dans le fichier Excel ?", style: TextStyle(color: Colories.unselected)),
          actions: [
            TextButton(
              child: Text("Non", style: TextStyle(color: Colories.unselected)),
              onPressed: () {
                Navigator.of(context).pop();
                _exportData(false);
              },
            ),
            ElevatedButton(
              style: ElevatedButton.styleFrom(backgroundColor: Colories.selected),
              child: Text("Oui", style: TextStyle(color: Colories.background)),
              onPressed: () {
                if (SheetPage.selectedMatiere == null) {
                  _showWarningMatiereUnselected();
                } else {
                  Navigator.of(context).pop();
                  _exportData(true);
                }
              },
            ),
          ],
        );
      },
    );
  }

  void _exportData(bool includeCardId) async {
    final filePath = await DatabaseHelper.instance.generateExcel(includeCardId);
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(filePath != null
            ? 'Fichier Excel généré : $filePath'
            : 'Aucune donnée à exporter.'),
        backgroundColor: filePath != null ? Colories.selected : Colors.red,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colories.background,
      appBar: AppBar(
        title: Text('Données des étudiants', style: TextStyle(color: Colories.selected)),
        backgroundColor: Colories.background,
        elevation: 0,
        centerTitle: true,
      ),
      body: FutureBuilder<List<Student>>(
        future: _students,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return Center(child: CircularProgressIndicator(color: Colories.selected));
          } else if (snapshot.hasError) {
            return Center(child: Text('Erreur: ${snapshot.error}', style: TextStyle(color: Colors.red)));
          } else if (!snapshot.hasData || snapshot.data!.isEmpty) {
            return Center(child: Text('Aucun étudiant enregistré.', style: TextStyle(color: Colories.unselected)));
          } else {
            final students = snapshot.data!;
            return SingleChildScrollView(
              child: SingleChildScrollView(
                scrollDirection: Axis.horizontal,
                child: DataTable(
                  columnSpacing: 20.0,
                  headingRowColor: WidgetStateColor.resolveWith((states) => Colories.subtitle),
                  columns: [
                    DataColumn(label: Text('ID Étudiant', style: TextStyle(color: Colories.selected, fontWeight: FontWeight.bold))),
                    DataColumn(label: Text('Prénom', style: TextStyle(color: Colories.selected, fontWeight: FontWeight.bold))),
                    DataColumn(label: Text('Nom', style: TextStyle(color: Colories.selected, fontWeight: FontWeight.bold))),
                    DataColumn(label: Text('Promotion', style: TextStyle(color: Colories.selected, fontWeight: FontWeight.bold))),
                  ],
                  rows: students.map((student) => DataRow(
                    cells: [
                      DataCell(Text(student.studentId, style: TextStyle(color: Colories.unselected))),
                      DataCell(Text(student.firstName, style: TextStyle(color: Colories.unselected))),
                      DataCell(Text(student.name, style: TextStyle(color: Colories.unselected))),
                      DataCell(Text(student.promotion, style: TextStyle(color: Colories.unselected))),
                    ],
                  )).toList(),
                ),
              ),
            );
          }
        },
      ),
      floatingActionButton: FloatingActionButton.extended(
        onPressed: _showExportDialog,
        label: Text('Générer le fichier', style: TextStyle(color: Colories.background)),
        icon: Icon(Icons.download, color: Colories.background),
        backgroundColor: Colories.selected,
      ),
    );
  }
}