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

class SheetPage extends StatefulWidget {
  const SheetPage({super.key});
  static String? selectedProgram;
  static String? selectedSubject;

  @override
  State<SheetPage> createState() => _SheetPageState();
}

class _SheetPageState extends State<SheetPage> {
  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 _showWarningSubjectUnselected() {
    showDialog(context: context, builder: (BuildContext context) {
      return AlertDialog(
        backgroundColor: AppColors.background,
        title: Text("WARNING !", style: TextStyle(color: AppColors.warning)),
        content: Text("Vous n'avez pas sélectionnez de matière dans l'application. Continuez quand même ?", style: TextStyle(color: AppColors.unselected)),
        actions: [
          TextButton(
            child: Text("Non", style: TextStyle(color: AppColors.unselected)),
            onPressed: () {
              Navigator.of(context).pop();
            },
          ),
          ElevatedButton(
            style: ElevatedButton.styleFrom(backgroundColor: AppColors.selected),
            child: Text("Oui", style: TextStyle(color: AppColors.background)),
            onPressed: () {
              Navigator.of(context).pop();
              _exportData(true);
            },
          ),
        ],
      );
    });
  }

  void _showExportDialog() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          backgroundColor: AppColors.background,
          title: Text("Exporter les données", style: TextStyle(color: AppColors.selected)),
          content: Text("Voulez-vous inclure la colonne 'ID Carte' dans le fichier Excel ?", style: TextStyle(color: AppColors.unselected)),
          actions: [
            TextButton(
              child: Text("Non", style: TextStyle(color: AppColors.unselected)),
              onPressed: () {
                Navigator.of(context).pop();
                _exportData(false);
              },
            ),
            ElevatedButton(
              style: ElevatedButton.styleFrom(backgroundColor: AppColors.selected),
              child: Text("Oui", style: TextStyle(color: AppColors.background)),
              onPressed: () {
                if (SheetPage.selectedSubject == null) {
                  _showWarningSubjectUnselected();
                } else {
                  Navigator.of(context).pop();
                  _exportData(true);
                }
              },
            ),
          ],
        );
      },
    );
  }

  void _exportData(bool includeCardId) async {
    final List<int>? excelBytes = await DatabaseHelper.instance.generateExcel(includeCardId);

    if (excelBytes == null) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('Aucune donnée à exporter.'),
          backgroundColor: Colors.red,
        ),
      );
      return;
    }

    String? filePath = await FilePicker.platform.saveFile(
      dialogTitle: 'Veuillez sélectionner un emplacement de sortie',
      fileName: '${SheetPage.selectedProgram ?? 'Program'}_${SheetPage.selectedSubject ?? 'Subject'}_${DateTime.now().year}.xlsx',
      bytes: Uint8List.fromList(excelBytes),
    );

    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(filePath != null
            ? 'Fichier Excel enregistré avec succès !'
            : 'Enregistrement annulé.'),
        backgroundColor: filePath != null ? AppColors.selected : Colors.orange,
      ),
    );
  }

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