import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'dart:math' as math; // Pour la rotation du chevron
import '../../../models/parent_user_registration_data.dart'; // Import du modèle
import '../../../utils/data_generator.dart'; // Import du générateur
import '../../../widgets/custom_app_text_field.dart'; // Import du widget
import '../../../models/card_assets.dart'; // Import des enums de cartes

class ParentRegisterStep2Screen extends StatefulWidget {
  final UserRegistrationData registrationData; // Accepte les données de l'étape 1

  const ParentRegisterStep2Screen({super.key, required this.registrationData});

  @override
  State<ParentRegisterStep2Screen> createState() => _ParentRegisterStep2ScreenState();
}

class _ParentRegisterStep2ScreenState extends State<ParentRegisterStep2Screen> {
  final _formKey = GlobalKey<FormState>();
  late UserRegistrationData _registrationData; // Copie locale pour modification

  bool _addParent2 = true; // Pour le test, on ajoute toujours le parent 2
  bool _sameAddressAsParent1 = false; // Peut être généré aléatoirement aussi

  // Contrôleurs pour les champs du parent 2 (restauration CP et Ville)
  final _lastNameController = TextEditingController();
  final _firstNameController = TextEditingController();
  final _phoneController = TextEditingController();
  final _emailController = TextEditingController();
  final _passwordController = TextEditingController();
  final _confirmPasswordController = TextEditingController();
  final _addressController = TextEditingController(); // Rue seule
  final _postalCodeController = TextEditingController(); // Restauré
  final _cityController = TextEditingController(); // Restauré

  @override
  void initState() {
    super.initState();
    _registrationData = widget.registrationData; // Récupère les données de l'étape 1
    if (_addParent2) {
      _generateAndFillParent2Data();
    }
  }

  void _generateAndFillParent2Data() {
    final String genFirstName = DataGenerator.firstName();
    final String genLastName = DataGenerator.lastName();
    _firstNameController.text = genFirstName;
    _lastNameController.text = genLastName;
    _phoneController.text = DataGenerator.phone();
    _emailController.text = DataGenerator.email(genFirstName, genLastName);
    _passwordController.text = DataGenerator.password();
    _confirmPasswordController.text = _passwordController.text;
    
    _sameAddressAsParent1 = DataGenerator.boolean(); 
    if (!_sameAddressAsParent1) {
      // Générer adresse, CP, Ville séparément
      _addressController.text = DataGenerator.address(); 
      _postalCodeController.text = DataGenerator.postalCode();
      _cityController.text = DataGenerator.city();
    } else {
      // Vider les champs si même adresse (seront désactivés)
      _addressController.clear();
      _postalCodeController.clear();
      _cityController.clear();
    }
  }

  @override
  void dispose() {
    _lastNameController.dispose();
    _firstNameController.dispose();
    _phoneController.dispose();
    _emailController.dispose();
    _passwordController.dispose();
    _confirmPasswordController.dispose();
    _addressController.dispose();
    _postalCodeController.dispose();
    _cityController.dispose();
    super.dispose();
  }
  
  bool get _parent2FieldsEnabled => _addParent2;
  bool get _addressFieldsEnabled => _addParent2 && !_sameAddressAsParent1;

  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;

    return Scaffold(
      body: Stack(
        children: [
          Positioned.fill(
            child: Image.asset('assets/images/paper2.png', fit: BoxFit.cover, repeat: ImageRepeat.repeat),
          ),
          Center(
            child: SingleChildScrollView(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text('Étape 2/5', style: GoogleFonts.merienda(fontSize: 16, color: Colors.black54)),
                  const SizedBox(height: 10),
                  Text(
                    'Informations du Deuxième Parent (Optionnel)',
                    style: GoogleFonts.merienda(fontSize: 24, fontWeight: FontWeight.bold, color: Colors.black87),
                    textAlign: TextAlign.center,
                  ),
                  const SizedBox(height: 30),
                  Container(
                    width: screenSize.width * 0.6,
                    padding: const EdgeInsets.symmetric(vertical: 40, horizontal: 50),
                    decoration: BoxDecoration(
                      image: DecorationImage(image: AssetImage(CardColorHorizontal.blue.path), fit: BoxFit.fill),
                    ),
                    child: Form(
                      key: _formKey,
                      child: SingleChildScrollView(
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Row(
                               crossAxisAlignment: CrossAxisAlignment.center,
                               children: [
                                 Expanded(
                                   flex: 12,
                                   child: Row(children: [
                                     const Icon(Icons.person_add_alt_1, size: 20), const SizedBox(width: 8),
                                     Flexible(child: Text('Ajouter Parent 2 ?', style: GoogleFonts.merienda(fontWeight: FontWeight.bold), overflow: TextOverflow.ellipsis)),
                                     const Spacer(),
                                     Switch(value: _addParent2, onChanged: (val) => setState(() {
                                       _addParent2 = val ?? false;
                                       if (_addParent2) _generateAndFillParent2Data(); else _clearParent2Fields();
                                     }), activeColor: Theme.of(context).primaryColor),
                                   ]),
                                 ),
                                 Expanded(flex: 1, child: const SizedBox()),
                                 Expanded(
                                   flex: 12,
                                   child: Row(children: [
                                     Icon(Icons.home_work_outlined, size: 20, color: _addParent2 ? null : Colors.grey),
                                     const SizedBox(width: 8),
                                     Flexible(child: Text('Même Adresse ?', style: GoogleFonts.merienda(color: _addParent2 ? null : Colors.grey), overflow: TextOverflow.ellipsis)),
                                     const Spacer(),
                                     Switch(value: _sameAddressAsParent1, onChanged: _addParent2 ? (val) => setState(() {
                                       _sameAddressAsParent1 = val ?? false;
                                       if (_sameAddressAsParent1) {
                                         _addressController.text = _registrationData.parent1.address;
                                         _postalCodeController.text = _registrationData.parent1.postalCode;
                                         _cityController.text = _registrationData.parent1.city;
                                       } else {
                                         _addressController.text = DataGenerator.address();
                                         _postalCodeController.text = DataGenerator.postalCode();
                                         _cityController.text = DataGenerator.city();
                                       }
                                     }) : null, activeColor: Theme.of(context).primaryColor),
                                   ]),
                                 ),
                               ]),
                            const SizedBox(height: 25),
                            Row(
                              children: [
                                Expanded(flex: 12, child: CustomAppTextField(controller: _lastNameController, labelText: 'Nom', hintText: 'Nom du parent 2', enabled: _parent2FieldsEnabled, style: CustomAppTextFieldStyle.beige, fieldWidth: double.infinity)),
                                Expanded(flex: 1, child: const SizedBox()), // Espace de 4%
                                Expanded(flex: 12, child: CustomAppTextField(controller: _firstNameController, labelText: 'Prénom', hintText: 'Prénom du parent 2', enabled: _parent2FieldsEnabled, style: CustomAppTextFieldStyle.beige, fieldWidth: double.infinity)),
                              ],
                            ),
                            const SizedBox(height: 20),
                            Row(
                              children: [
                                Expanded(flex: 12, child: CustomAppTextField(controller: _phoneController, labelText: 'Téléphone', keyboardType: TextInputType.phone, hintText: 'Son téléphone', enabled: _parent2FieldsEnabled, style: CustomAppTextFieldStyle.beige, fieldWidth: double.infinity)),
                                Expanded(flex: 1, child: const SizedBox()), // Espace de 4%
                                Expanded(flex: 12, child: CustomAppTextField(controller: _emailController, labelText: 'Email', keyboardType: TextInputType.emailAddress, hintText: 'Son email', enabled: _parent2FieldsEnabled, style: CustomAppTextFieldStyle.beige, fieldWidth: double.infinity)),
                              ],
                            ),
                            const SizedBox(height: 20),
                            Row(
                              children: [
                                Expanded(flex: 12, child: CustomAppTextField(controller: _passwordController, labelText: 'Mot de passe', obscureText: true, hintText: 'Son mot de passe', enabled: _parent2FieldsEnabled, style: CustomAppTextFieldStyle.beige, fieldWidth: double.infinity, validator: _addParent2 ? (v) => (v == null || v.isEmpty ? 'Requis' : (v.length < 6 ? '6 car. min' : null)) : null)),
                                Expanded(flex: 1, child: const SizedBox()), // Espace de 4%
                                Expanded(flex: 12, child: CustomAppTextField(controller: _confirmPasswordController, labelText: 'Confirmation', obscureText: true, hintText: 'Confirmer mot de passe', enabled: _parent2FieldsEnabled, style: CustomAppTextFieldStyle.beige, fieldWidth: double.infinity, validator: _addParent2 ? (v) => (v == null || v.isEmpty ? 'Requis' : (v != _passwordController.text ? 'Différent' : null)) : null)),
                              ],
                            ),
                            const SizedBox(height: 20),
                            CustomAppTextField(controller: _addressController, labelText: 'Adresse (N° et Rue)', hintText: 'Son numéro et nom de rue', enabled: _addressFieldsEnabled, style: CustomAppTextFieldStyle.beige, fieldWidth: double.infinity),
                            const SizedBox(height: 20),
                            Row(
                              children: [
                                Expanded(flex: 1, child: CustomAppTextField(controller: _postalCodeController, labelText: 'Code Postal', keyboardType: TextInputType.number, hintText: 'Son code postal', enabled: _addressFieldsEnabled, style: CustomAppTextFieldStyle.beige, fieldWidth: double.infinity)),
                                const SizedBox(width: 20),
                                Expanded(flex: 4, child: CustomAppTextField(controller: _cityController, labelText: 'Ville', hintText: 'Sa ville', enabled: _addressFieldsEnabled, style: CustomAppTextFieldStyle.beige, fieldWidth: double.infinity)),
                              ],
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
          Positioned(
            top: screenSize.height / 2 - 20,
            left: 40,
            child: IconButton(
              icon: Transform(alignment: Alignment.center, transform: Matrix4.rotationY(math.pi), child: Image.asset('assets/images/chevron_right.png', height: 40)),
              onPressed: () => Navigator.pop(context),
              tooltip: 'Retour',
            ),
          ),
          Positioned(
            top: screenSize.height / 2 - 20,
            right: 40,
            child: IconButton(
              icon: Image.asset('assets/images/chevron_right.png', height: 40),
              onPressed: () {
                if (!_addParent2 || (_formKey.currentState?.validate() ?? false)) {
                  if (_addParent2) {
                    _registrationData.updateParent2(
                      ParentData(
                        firstName: _firstNameController.text,
                        lastName: _lastNameController.text,
                        address: _sameAddressAsParent1 ? _registrationData.parent1.address : _addressController.text,
                        postalCode: _sameAddressAsParent1 ? _registrationData.parent1.postalCode : _postalCodeController.text,
                        city: _sameAddressAsParent1 ? _registrationData.parent1.city : _cityController.text,
                        phone: _phoneController.text,
                        email: _emailController.text,
                        password: _passwordController.text,
                      )
                    );
                  } else {
                    _registrationData.updateParent2(null);
                  }
                  Navigator.pushNamed(context, '/parent-register/step3', arguments: _registrationData);
                }
              },
              tooltip: 'Suivant',
            ),
          ),
        ],
      ),
    );
  }

  void _clearParent2Fields() {
    _formKey.currentState?.reset();
    _lastNameController.clear(); _firstNameController.clear(); _phoneController.clear();
    _emailController.clear(); _passwordController.clear(); _confirmPasswordController.clear();
    _addressController.clear(); 
    _postalCodeController.clear();
    _cityController.clear();
    _sameAddressAsParent1 = false;
    setState(() {});
  }
} 