import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:english_learning/core/utils/styles/theme.dart';
import 'package:english_learning/features/auth/provider/validator_provider.dart';

class LoginEmailField extends StatefulWidget {
  const LoginEmailField({super.key});

  @override
  _LoginEmailFieldState createState() => _LoginEmailFieldState();
}

class _LoginEmailFieldState extends State<LoginEmailField> {
  late FocusNode _focusNode;

  @override
  void initState() {
    super.initState();
    _focusNode = FocusNode();

    _focusNode.addListener(() {
      if (!_focusNode.hasFocus) {
        final validatorProvider =
            Provider.of<ValidatorProvider>(context, listen: false);
        validatorProvider.validateField(
            'email', validatorProvider.getError('email'),
            validator: validatorProvider.emailValidator);
      }
    });
  }

  @override
  void dispose() {
    _focusNode.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final validatorProvider = Provider.of<ValidatorProvider>(context);
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          'Email',
          style: AppTextStyles.blackTextStyle.copyWith(
            fontSize: 12,
            fontWeight: FontWeight.bold,
          ),
        ),
        const SizedBox(height: 8),
        TextField(
          focusNode: _focusNode,
          keyboardType: TextInputType.emailAddress,
          onChanged: (value) {
            validatorProvider.validateField('email', value,
                validator: validatorProvider.emailValidator);
          },
          decoration: InputDecoration(
            hintText: 'Enter Your Email Address',
            hintStyle: AppTextStyles.disableTextStyle.copyWith(
              fontSize: 12,
            ),
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(8),
              borderSide: const BorderSide(
                color: AppColors.disableColor,
                width: 1,
              ),
            ),
            errorText: validatorProvider.getError('email'),
          ),
        )
      ],
    );
  }
}
