import 'package:flutter/material.dart';
import 'package:prosapp_web_app/providers/auth_provider.dart';
import 'package:prosapp_web_app/providers/phone_form_provider.dart';
import 'package:prosapp_web_app/ui/buttons/custom_outlined_button.dart';
import 'package:prosapp_web_app/ui/cards/white_card.dart';
import 'package:prosapp_web_app/ui/inputs/custom_inputs.dart';
import 'package:provider/provider.dart';

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

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

    final TextEditingController _phoneController = TextEditingController();

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

        return ListView(
          physics: const ClampingScrollPhysics(),
          children: [
            Center(
              child: ConstrainedBox(
                constraints: const BoxConstraints(maxWidth: 900),
                child: WhiteCard(
                  child: Column(
                    children: [
                      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: phoneFormProvider.formKey,
                              child: Column(
                                children: [
                                  TextFormField(
                                    controller: _phoneController,
                                    validator: (value) {
                                      if (value == null ||
                                          value.isEmpty ||
                                          value.length < 10) {
                                        return 'Ingresa un número de teléfono válido';
                                      }
                                      return null;
                                    },
                                    onChanged: (value) {
                                      phoneFormProvider.phone =
                                          '+57${value.trim()}';
                                    },
                                    keyboardType: TextInputType.phone,
                                    decoration:
                                        CustomInputs.loginInputDecoration(
                                      hint: 'Ingresa tu número de teléfono',
                                      label: 'Número de Teléfono',
                                      icon: Icons.phone_android_outlined,
                                    ),
                                  ),
                                  const SizedBox(height: 20),
                                  CustomOutlinedButton(
                                    onPressed: () async {
                                      final isValid =
                                          phoneFormProvider.validateForm();
                                      if (isValid) {
                                        await authProvider
                                            .verifyPhoneNumberForLink(
                                                phoneFormProvider.phone);

                                        showDialog(
                                          context: context,
                                          builder: (context) => _buildOtpModal(
                                              context, authProvider, phoneFormProvider.phone),
                                        );
                                      }
                                    },
                                    text: "Enviar código",
                                    color: Colors.blue,
                                  ),
                                  const SizedBox(height: 20),
                                ],
                              ),
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ],
        );
      }),
    );
  }

  Widget _buildOtpModal(BuildContext context, AuthProvider authProvider, String phone) {
    final _otpController = TextEditingController();

    return AlertDialog(
      title: const Text('Ingresar código OTP'),
      content: TextField(
        controller: _otpController,
        decoration: const InputDecoration(labelText: 'Código OTP'),
        keyboardType: TextInputType.number,
      ),
      actions: [
        TextButton(
          onPressed: () {
            Navigator.of(context).pop();
          },
          child: const Text('Cancelar'),
        ),
        ElevatedButton(
          onPressed: () async {
            final otp = _otpController.text.trim();

            if (otp.isNotEmpty) {
              await authProvider.linkPhoneWithOTP(phone, otp);
              Navigator.of(context).pop();
            } else {
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(
                    content: Text('Por favor ingresa el código OTP')),
              );
            }
          },
          child: const Text('Verificar OTP'),
        ),
      ],
    );
  }
}
