import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:zabino/features/codex_solution/presentation/components/box_decoration_custom.dart';
import 'package:zabino/features/codex_solution/presentation/components/input_decoration_custom.dart';
import 'package:zabino/features/codex_solution/presentation/provider/state/text_field_state.dart';
import 'package:zabino/features/codex_solution/presentation/provider/text_field_controller.dart';

class TexFieldCustom extends ConsumerWidget {
  const TexFieldCustom({
    super.key,
    required this.label,
    required this.prefixIcon,
    this.maxLine = 1,
    this.onTaped,
    required this.controller,
    this.onTapDrapDown,
    this.readOnly = false,
    this.keyboardType = TextInputType.text,
    this.onChange,
  });
  final String label;
  final IconData prefixIcon;
  final int maxLine;
  final TextEditingController controller;
  final Function(String)? onTaped;
  final Function()? onTapDrapDown;
  final Function(String value)? onChange;
  final bool? readOnly;
  final TextInputType? keyboardType;

  final double radius = 16;

  @override
  Widget build(BuildContext context, ref) {
    final state = ref.watch(textFieldControllerProvider);
    final selectedTextFieldName = ref.watch(
      textFieldControllerProvider.select(
        (state) => state.selectedTextFieldName,
      ),
    );
    final manageStateTextField = ref.read(textFieldControllerProvider.notifier);
    return Container(
      decoration: BoxDecorationCustom(state, label),
      child: TextField(
        controller: controller,
        keyboardType: keyboardType,
        contextMenuBuilder: (context, editableTextState) {
          return const Icon(Icons.close);
        },
        onChanged: onChange != null
            ? (value) {
                manageStateTextField.setEmptyTextField(value, label);
                onChange?.call(value);
              }
            : (value) {
                manageStateTextField.setEmptyTextField(value, label);
              },

        onTap: readOnly!
            ? () {
                onTapDrapDown!();
              }
            : () {
                manageStateTextField.setEmptyTextField(controller.text, label);

                onTaped!(label);
              },
        readOnly: readOnly!,
        cursorHeight: 12,
        autofocus: true,
        maxLines: maxLine,
        style: const TextStyle(fontSize: 14),
        textAlignVertical: TextAlignVertical.center,
        decoration: InputDecorationCustom(
          radius,
          label,
          prefixIcon,
          controller,
          onTapDrapDown,
          selectedTextFieldName,
          state,
          manageStateTextField,
        ),
      ),
    );
  }
}
