import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:go_router/go_router.dart';

import '../../models/user_registration_data.dart';
import '../../widgets/personal_info_form_screen.dart';
import '../../models/card_assets.dart';

class ParentRegisterStep2Screen extends StatelessWidget {
  const ParentRegisterStep2Screen({super.key});

  @override
  Widget build(BuildContext context) {
    final registrationData = Provider.of<UserRegistrationData>(context, listen: false);
    final parent1 = registrationData.parent1;
    final parent2 = registrationData.parent2;
    
    bool hasParent2 = parent2 != null;
    bool sameAddress = false;
    
    PersonalInfoData initialData;
    if (parent2 == null || parent2.firstName.isEmpty) {
      sameAddress = false;
      initialData = PersonalInfoData(
        firstName: parent2?.firstName ?? '',
        lastName: parent2?.lastName ?? '',
        phone: parent2?.phone ?? '',
        email: parent2?.email ?? '',
        address: parent2?.address ?? '',
        postalCode: parent2?.postalCode ?? '',
        city: parent2?.city ?? '',
      );
    } else {
      sameAddress = (parent2.address == parent1.address && 
                     parent2.postalCode == parent1.postalCode && 
                     parent2.city == parent1.city);
      initialData = PersonalInfoData(
        firstName: parent2.firstName,
        lastName: parent2.lastName,
        phone: parent2.phone,
        email: parent2.email,
        address: parent2.address,
        postalCode: parent2.postalCode,
        city: parent2.city,
      );
    }

    // Adresse de référence pour "même adresse"
    final referenceAddress = PersonalInfoData(
      address: parent1.address,
      postalCode: parent1.postalCode,
      city: parent1.city,
    );

    return PersonalInfoFormScreen(
      stepText: 'Étape 2/5',
      title: 'Deuxième Parent',
      cardColor: CardColorHorizontal.blue,
      initialData: initialData,
      previousRoute: '/parent-register-step1',
      showSecondPersonToggle: true,
      initialHasSecondPerson: hasParent2,
      showSameAddressCheckbox: true,
      initialSameAddress: sameAddress,
      referenceAddressData: referenceAddress,
      onSubmit: (data, {hasSecondPerson, sameAddress}) {
        if (hasSecondPerson == true) {
          registrationData.updateParent2(ParentData(
            firstName: data.firstName,
            lastName: data.lastName,
            phone: data.phone,
            email: data.email,
            address: data.address,
            postalCode: data.postalCode,
            city: data.city,
            password: '',
          ));
        } else {
          registrationData.updateParent2(null);
        }
        context.go('/parent-register-step3');
      },
    );
  }
}
