import 'package:flutter/material.dart';
import 'package:p_tits_pas/models/am_user_registration_data.dart';
import 'package:p_tits_pas/models/card_assets.dart';
import 'package:p_tits_pas/utils/data_generator.dart';
import 'package:p_tits_pas/widgets/FormFieldConfig.dart';
import 'package:google_fonts/google_fonts.dart';
import 'dart:math' as math;


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

class _AmRegisterStep1ScreenState extends State<AmRegisterStep1Screen> {
  final _formKey = GlobalKey<FormState>();
  late ChildminderRegistrationData _registrationData;

  final _lastNameController = TextEditingController();
  final _firstNameController = TextEditingController();
  final _phoneController = TextEditingController();
  final _emailController = TextEditingController();
  final _passwordController = TextEditingController();
  final _confirmPasswordController = TextEditingController();
  final _addressController = TextEditingController();
  final _postalCodeController = TextEditingController();
  final _cityController = TextEditingController();

  // File? _selectedImage;
  // bool _photoConsent = false;
  // final ImagePicker _picker = ImagePicker();


  @override
  void initState() {
    super.initState();
    _registrationData = ChildminderRegistrationData();
    _generateAndFillData();
  }

  void _generateAndFillData() {
    final String genFirstName = DataGenerator.firstName();
    final String genLastName = DataGenerator.lastName();
    final String genAddress = DataGenerator.address();
    final String genPostalCode = DataGenerator.postalCode();
    final String genCity = DataGenerator.city();
    final String genPhone = DataGenerator.phone();
    final String genEmail = DataGenerator.email(genFirstName, genLastName);
    final String genPassword = DataGenerator.password();

    _addressController.text = genAddress;
    _postalCodeController.text = genPostalCode;
    _cityController.text = genCity;
    _firstNameController.text = genFirstName;
    _lastNameController.text = genLastName;
    _phoneController.text = genPhone;
    _emailController.text = genEmail;
    _passwordController.text = genPassword;
    _confirmPasswordController.text = genPassword;

    setState(() {
      _registrationData.updateIdentity(
        ChildminderId(
          firstName: genFirstName,
          lastName: genLastName,
          address: genAddress,
          postalCode: genPostalCode,
          city: genCity,
          phone: genPhone,
          email: genEmail,
          password: genPassword.trim(),
        ),
      );
    });
  }

  @override
  void dispose() {
    _lastNameController.dispose();
    _firstNameController.dispose();
    _phoneController.dispose();
    _emailController.dispose();
    _passwordController.dispose();
    _confirmPasswordController.dispose();
    _addressController.dispose();
    _postalCodeController.dispose();
    _cityController.dispose();
    super.dispose();
  }

  List<List<ModularFormField>> get formFields => [
    [
      ModularFormField(
        label: 'Nom',
        hint: 'Votre nom de famille',
        controller: _lastNameController,
        isRequired: true,
        flex: 12,
      ),
      ModularFormField(
        label: 'Prénom',
        hint: 'Votre prénom',
        controller: _firstNameController,
        isRequired: true,
        flex: 12,
      ),
    ],
    [
      ModularFormField(
        label: 'Téléphone',
        hint: 'Votre numéro de téléphone',
        controller: _phoneController,
        keyboardType: TextInputType.phone,
        flex: 12,
      ),
      ModularFormField(
        label: 'Email',
        hint: 'Votre adresse email',
        controller: _emailController,
        keyboardType: TextInputType.emailAddress,
        flex: 12,
      ),
    ],
    [
      ModularFormField(
        label: 'Mot de passe',
        hint: 'Votre mot de passe',
        controller: _passwordController,
        isPassword: true,
        validator: (value) {
          if (value == null || value.isEmpty) return 'Mot de passe requis';
          if (value.length < 6) return '6 caractères minimum';
          return null;
        },
        isRequired: true,
        flex: 12,
      ),
      ModularFormField(
        label: 'Confirmer le mot de passe',
        hint: 'Confirmez votre mot de passe',
        controller: _confirmPasswordController,
        isPassword: true,
        validator: (value) {
          if (value == null || value.isEmpty) return 'Mot de passe requis';
          if (value != _passwordController.text) return 'Les mots de passe ne correspondent pas';
          return null;
        },
        isRequired: true,
        flex: 12,
      ),
    ],
    [
      ModularFormField(
        label: 'Adresse (N° et Rue)',
        hint: 'Numéro et nom de votre rue',
        controller: _addressController,
        isRequired: true,
      ),
    ],
    [
      ModularFormField(
        label: 'Code postal',
        hint: 'Votre code postal',
        controller: _postalCodeController,
        keyboardType: TextInputType.number,
        isRequired: true,
        flex: 1,
      ),
      ModularFormField(
        label: 'Ville',
        hint: 'Votre ville',
        controller: _cityController,
        flex: 4,
        isRequired: true,
      ),
    ],
  ];

  void _handleSubmit() {
    if (_formKey.currentState?.validate() ?? false) {
      _registrationData.updateIdentity(
        ChildminderId(
          firstName: _firstNameController.text,
          lastName: _lastNameController.text,
          address: _addressController.text,
          postalCode: _postalCodeController.text,
          city: _cityController.text,
          phone: _phoneController.text,
          email: _emailController.text,
          password: _passwordController.text,
        ),
      );
      print('Vérification des données:');
      print('Adresse: ${_registrationData.identity.address}');
      print('Nom: ${_registrationData.identity.lastName}');
      print('Prénom: ${_registrationData.identity.firstName}');
      Navigator.pushNamed(context, '/am-register/step2',
          arguments: _registrationData);
    }
  }

  @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 1/4',
                    style: GoogleFonts.merienda(fontSize: 16, color: Colors.black54),
                  ),
                  const SizedBox(height: 10),
                  Text(
                    'Informations d\'identité de l\'assistante maternelle',
                    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: 50, horizontal: 50),
                    constraints: const BoxConstraints(minHeight: 570),
                    decoration: BoxDecoration(
                      image: DecorationImage(
                        image: AssetImage(CardColorHorizontal.lavender.path),
                        fit: BoxFit.fill,
                      ),
                    ),
                    child: ModularForm(
                      formKey: _formKey,
                      fieldGroups: formFields,
                    ),
                  ),
                ],
              ),
            ),
          ),
          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: _handleSubmit,
              tooltip: 'Suivant',
            ),
          ),
        ],
      ),
    );
  }
}