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

class EmailFieldWidget extends StatefulWidget {
  final String labelText;
  final String hintText;
  const EmailFieldWidget(
      {super.key, required this.labelText, required this.hintText});

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

class _EmailFieldWidgetState extends State<EmailFieldWidget> {
  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(
          widget.labelText,
          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: widget.hintText,
            hintStyle: AppTextStyles.disableTextStyle.copyWith(
              fontSize: 12,
            ),
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(8),
              borderSide: const BorderSide(
                width: 1,
                color: AppColors.disableColor,
              ),
            ),
            errorText: validatorProvider.getError('email'),
          ),
        ),
      ],
    );
  }
}
