import 'package:flutter/material.dart';
import 'package:nfc_google_sheet/context/app_colors.dart';
import 'package:nfc_google_sheet/database/student_dao.dart';
import 'package:nfc_google_sheet/model/student.dart';
import 'package:nfc_google_sheet/services/program_service.dart';

class StudentForm extends StatefulWidget {
  final String cardId;
  final Function(Student)? onStudentSaved;

  const StudentForm({super.key, required this.cardId, this.onStudentSaved});

  @override
  _StudentFormState createState() => _StudentFormState();
}

class _StudentFormState extends State<StudentForm> {
  final _formKey = GlobalKey<FormState>();
  final _studentIdController = TextEditingController();
  final _firstNameController = TextEditingController();
  final _nameController = TextEditingController();
  String? _selectedPromotion;
  List<String> _promotions = [];

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

  Future<void> _loadPromotions() async {
    final promotions = await ProgramService.instance.getPromotionNames();
    setState(() {
      _promotions = promotions;
    });
  }

  Widget _buildTextField(TextEditingController controller, String label, String errorMessage) {
    return TextFormField(
      controller: controller,
      style: TextStyle(color: AppColors.unselected),
      decoration: InputDecoration(
        labelText: label,
        labelStyle: TextStyle(color: AppColors.unselected),
        enabledBorder: UnderlineInputBorder(
          borderSide: BorderSide(color: AppColors.unselected),
        ),
      ),
      validator: (value) {
        if (value == null || value.isEmpty) {
          return errorMessage;
        }
        return null;
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      backgroundColor: AppColors.background,
      title: Text(
        'Nouvel étudiant',
        style: TextStyle(color: AppColors.selected),
      ),
      content: Form(
        key: _formKey,
        child: SingleChildScrollView(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              _buildTextField(_studentIdController, 'ID Etudiant', 'Veuillez entrer l\'ID de l\'étudiant'),
              _buildTextField(_firstNameController, 'Prénom', 'Veuillez entrer le prénom'),
              _buildTextField(_nameController, 'Nom', 'Veuillez entrer le nom'),
              DropdownButtonFormField<String>(
                initialValue: _selectedPromotion,
                dropdownColor: AppColors.background,
                style: TextStyle(color: AppColors.unselected),
                decoration: InputDecoration(
                  labelText: 'Promotion',
                  labelStyle: TextStyle(color: AppColors.unselected),
                  enabledBorder: UnderlineInputBorder(
                    borderSide: BorderSide(color: AppColors.unselected),
                  ),
                ),
                items: _promotions.map((promo) {
                  return DropdownMenuItem(value: promo, child: Text(promo));
                }).toList(),
                onChanged: (value) {
                  setState(() {
                    _selectedPromotion = value;
                  });
                },
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return 'Veuillez sélectionner une promotion';
                  }
                  return null;
                },
              ),
            ],
          ),
        ),
      ),
      actions: <Widget>[
        TextButton(
          child: Text('Annuler', style: TextStyle(color: AppColors.unselected)),
          onPressed: () => Navigator.of(context).pop(),
        ),
        ElevatedButton(
          style: ElevatedButton.styleFrom(backgroundColor: AppColors.selected),
          child: Text('Enregistrer', style: TextStyle(color: AppColors.background)),
          onPressed: () async {
            if (_formKey.currentState!.validate()) {
              final student = Student(
                cardId: widget.cardId,
                studentId: _studentIdController.text,
                firstName: _firstNameController.text,
                name: _nameController.text,
                promotion: _selectedPromotion!,
              );
              await StudentDao.instance.insert(student);
              if (!mounted) return;
              Navigator.of(context).pop();
              widget.onStudentSaved?.call(student);
            }
          },
        ),
      ],
    );
  }
}
