import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import '../../../../../application/auth/check_phone_form/check_phone_form_bloc.dart';
import '../../../../../common/theme/theme.dart';
import '../../../../components/field/field.dart';

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

  @override
  State<LoginPhoneField> createState() => _LoginPhoneFieldState();
}

class _LoginPhoneFieldState extends State<LoginPhoneField> {
  final TextEditingController _controller = TextEditingController();
  final FocusNode _focusNode = FocusNode();
  bool _hasFocus = false;

  @override
  void initState() {
    super.initState();
    _focusNode.addListener(() {
      setState(() {
        _hasFocus = _focusNode.hasFocus;
      });
    });
  }

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

  void _clearText() {
    _controller.clear();
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return AppTextFormField(
      title: 'Masukkan no telepon',
      hintText: '8712671212',
      controller: _controller,
      focusNode: _focusNode,
      keyboardType: TextInputType.phone,
      validator: (value) {
        if (context.read<CheckPhoneFormBloc>().state.phoneNumber.isEmpty) {
          return 'Masukkan no telepon';
        }

        return null;
      },
      prefixIcon: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 12),
        child: Text(
          '+62',
          style: AppStyle.md.copyWith(
            color: AppColor.textPrimary,
            fontWeight: FontWeight.w500,
          ),
        ),
      ),
      suffixIcon: (_hasFocus && _controller.text.isNotEmpty)
          ? IconButton(
              onPressed: _clearText,
              icon: Icon(Icons.close, color: AppColor.primary, size: 20),
              constraints: const BoxConstraints(),
              padding: const EdgeInsets.all(8),
            )
          : null,
      onChanged: (value) {
        context.read<CheckPhoneFormBloc>().add(
          CheckPhoneFormEvent.phoneNumberChanged(value),
        );
      },
    );
  }
}
