import 'package:prosapp_web_app/providers/auth_provider.dart';
import 'package:prosapp_web_app/providers/register_form_provider.dart';
import 'package:prosapp_web_app/router/router.dart';
import 'package:prosapp_web_app/ui/buttons/custom_outlined_button.dart';
import 'package:prosapp_web_app/ui/buttons/link_text.dart';
import 'package:prosapp_web_app/ui/inputs/custom_inputs.dart';
import 'package:email_validator/email_validator.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

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

  @override
  Widget build(BuildContext context) {
    final authProvider = Provider.of<AuthProvider>(context);

    return ChangeNotifierProvider(
      create: (_) => RegisterFormProvider(),
      child: Builder(builder: (context) {
        final registerFormProvider =
            Provider.of<RegisterFormProvider>(context, listen: false);

        return Container(
          margin: const EdgeInsets.only(top: 40),
          padding: const EdgeInsets.symmetric(horizontal: 20),
          child: Center(
            child: ConstrainedBox(
              constraints: const BoxConstraints(maxWidth: 370),
              child: Form(
                autovalidateMode: AutovalidateMode.onUserInteraction,
                key: registerFormProvider.formKey,
                child: Column(
                  children: [
                    // Name
                    TextFormField(
                      validator: (value) {
                        if (value == null ||
                            value.isEmpty ||
                            value.trim().isEmpty) {
                          return 'El nombre es obligatorio';
                        }

                        if (value.trim().length < 3) {
                          return 'El nombre debe tener al menos 3 caracteres';
                        }
                        return null;
                      },
                      onChanged: (value) => registerFormProvider.name = value,
                      decoration: CustomInputs.loginInputDecoration(
                        hint: 'Ingrese su nombre',
                        label: 'Nombre',
                        icon: Icons.person_outline,
                      ),
                    ),
                    const SizedBox(height: 20),

                    // Email
                    TextFormField(
                      validator: (value) {
                        if (!EmailValidator.validate(value ?? '')) {
                          return 'Email no válido';
                        }
                        return null;
                      },
                      onChanged: (value) => registerFormProvider.email = value,
                      decoration: CustomInputs.loginInputDecoration(
                        hint: 'Ingresa tu correo',
                        label: 'Email',
                        icon: Icons.email_outlined,
                      ),
                    ),
                    const SizedBox(height: 20),

                    // Password
                    TextFormField(
                      validator: (value) {
                        if (value == null || value.length < 8) {
                          return "La contraseña debe tener al menos 8 caracteres";
                        }
                        return null;
                      },
                      onChanged: (value) =>
                          registerFormProvider.password = value,
                      obscureText: true,
                      decoration: CustomInputs.loginInputDecoration(
                        hint: 'Ingresa tu contraseña',
                        label: 'Contraseña',
                        icon: Icons.lock_outline,
                      ),
                    ),
                    const SizedBox(height: 20),

                    CustomOutlinedButton(
                      onPressed: () async {
                        final validForm = registerFormProvider.validateForm();

                        if (!validForm) return;

                        await authProvider.register(
                          registerFormProvider.email,
                          registerFormProvider.password,
                          registerFormProvider.name,
                        );
                      },
                      text: "Crear cuenta",
                      color: Colors.blue,
                    ),
                    const SizedBox(height: 20),

                    LinkText(
                      text: "Iniciar sesión",
                      onPressed: () {
                        Navigator.pushReplacementNamed(
                            context, Flurorouter.loginRoute);
                      },
                    ),
                    const SizedBox(height: 5),
                    LinkText(
                      text: "Entrar con celular",
                      onPressed: () {
                        Navigator.pushReplacementNamed(
                            context, Flurorouter.phoneLoginRoute);
                      },
                    ),
                  ],
                ),
              ),
            ),
          ),
        );
      }),
    );
  }
}
