import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:softplayer_web/features/authorization/application/authorization_application.dart';
import 'package:softplayer_web/features/authorization/application/sign_up_data.dart';

class RegisterForm extends ConsumerStatefulWidget {
  const RegisterForm({super.key, required this.toggleAuth});

  final VoidCallback toggleAuth;
  @override
  ConsumerState<RegisterForm> createState() => _RegisterForm();
}

class _RegisterForm extends ConsumerState<RegisterForm> {
  final _formKey = GlobalKey<FormState>();
  final emailCtrl = TextEditingController();
  final nameCtrl = TextEditingController();
  final surnameCtrl = TextEditingController();
  final passwordCtrl = TextEditingController();
  final repeatPasswordCtrl = TextEditingController();

  void _submitForm() {
    if (_formKey.currentState!.validate()) {
      // If valid, you can use the values
      final name = nameCtrl.text;
      final surname = surnameCtrl.text;
      final email = emailCtrl.text;
      final password = passwordCtrl.text;
      final data = SignUpData(
        email: email,
        password: password,
        name: name,
        surname: surname,
      );
      ref.read(authorizationControllerProvider.notifier).signup(data);
    }
  }

  @override
  Widget build(BuildContext context) {
    final controller = ref.read(authorizationControllerProvider.notifier);
    return SizedBox(
      width: 400,
      child: Form(
        key: _formKey,
        child: Column(
          children: [
            Container(
              alignment: Alignment.topLeft,
              child: SelectableText(
                "Welcome!",
                style: Theme.of(context).textTheme.headlineLarge,
              ),
            ),
            SizedBox(height: 12),
            Container(
              alignment: Alignment.topLeft,
              child: Row(
                children: [
                  Text(
                    "Already have an account? ",
                    style: Theme.of(context).textTheme.bodyMedium,
                  ),
                  TextButton(
                    onPressed: widget.toggleAuth,
                    style: TextButton.styleFrom(
                      padding: EdgeInsets.zero,
                      minimumSize: Size(0, 0),
                      tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                    ),
                    child: const Text(
                      "Sign in",
                      style: TextStyle(decoration: TextDecoration.underline),
                    ),
                  ),
                ],
              ),
            ),
            SizedBox(height: 36),
            TextFormField(
              controller: nameCtrl,
              onFieldSubmitted: (_) => _submitForm(),
              decoration: InputDecoration(hintText: "Name"),
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return 'Password is required';
                }
                return null;
              },
            ),
            SizedBox(height: 16),
            TextFormField(
              controller: surnameCtrl,
              onFieldSubmitted: (_) => _submitForm(),
              decoration: InputDecoration(hintText: "Surname"),
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return 'Password is required';
                }

                return null;
              },
            ),
            SizedBox(height: 16),
            TextFormField(
              controller: emailCtrl,
              onFieldSubmitted: (_) => _submitForm(),
              decoration: InputDecoration(hintText: "Email address"),
              validator: (value) {
                if (value == null || value.trim().isEmpty) {
                  return 'Email is required';
                }
                final emailRegex = RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$');
                if (!emailRegex.hasMatch(value.trim())) {
                  return 'Enter a valid email address';
                }
                return null;
              },
            ),
            SizedBox(height: 16),
            TextFormField(
              controller: passwordCtrl,
              onFieldSubmitted: (_) => _submitForm(),
              obscureText: true,
              decoration: InputDecoration(hintText: "Password"),
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return 'Password is required';
                }

                if (value.length < 12) {
                  return 'Password must be at least 12 characters long';
                }

                final hasNumber = RegExp(r'\d');
                final hasSpecialChar = RegExp(
                  r'[!@#$%^&*(),.?":{}|<>_\-\\[\]\\/+=~`]',
                );

                if (!hasNumber.hasMatch(value)) {
                  return 'Password must contain at least one number';
                }

                if (!hasSpecialChar.hasMatch(value)) {
                  return 'Password must contain at least one special character';
                }

                return null;
              },
            ),
            SizedBox(height: 16),
            TextFormField(
              controller: repeatPasswordCtrl,
              onFieldSubmitted: (_) => _submitForm(),
              obscureText: true,
              decoration: InputDecoration(hintText: "Repeat the password"),
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return 'Password is required';
                }

                if (value != passwordCtrl.text) {
                  return 'Passwords do not match';
                }

                return null;
              },
            ),
            SizedBox(height: 16),
            ElevatedButton(
              onPressed: _submitForm,
              child: const Text('Sign up'),
            ),
          ],
        ),
      ),
    );
  }
}
