import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../../core/constants/ui_constants.dart';

class ModernTextField extends StatefulWidget {
  final String? label;
  final String? hint;
  final String? helperText;
  final String? errorText;
  final TextEditingController? controller;
  final TextInputType? keyboardType;
  final bool obscureText;
  final bool enabled;
  final bool readOnly;
  final int? maxLines;
  final int? maxLength;
  final Widget? prefixIcon;
  final Widget? suffixIcon;
  final VoidCallback? onSuffixIconPressed;
  final String? Function(String?)? validator;
  final void Function(String)? onChanged;
  final void Function(String)? onSubmitted;
  final List<TextInputFormatter>? inputFormatters;
  final FocusNode? focusNode;
  final VoidCallback? onTap;
  final bool autofocus;
  final TextCapitalization textCapitalization;
  final TextInputAction? textInputAction;
  final bool expands;
  final double? height;
  final EdgeInsetsGeometry? contentPadding;

  const ModernTextField({
    super.key,
    this.label,
    this.hint,
    this.helperText,
    this.errorText,
    this.controller,
    this.keyboardType,
    this.obscureText = false,
    this.enabled = true,
    this.readOnly = false,
    this.maxLines = 1,
    this.maxLength,
    this.prefixIcon,
    this.suffixIcon,
    this.onSuffixIconPressed,
    this.validator,
    this.onChanged,
    this.onSubmitted,
    this.inputFormatters,
    this.focusNode,
    this.onTap,
    this.autofocus = false,
    this.textCapitalization = TextCapitalization.none,
    this.textInputAction,
    this.expands = false,
    this.height,
    this.contentPadding,
  });

  @override
  State<ModernTextField> createState() => _ModernTextFieldState();
}

class _ModernTextFieldState extends State<ModernTextField>
    with SingleTickerProviderStateMixin {
  late AnimationController _animationController;
  late Animation<double> _fadeAnimation;
  late Animation<double> _scaleAnimation;
  bool _isFocused = false;
  bool _hasError = false;
  late bool _obscureText;

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
      duration: UIConstants.durationFast,
      vsync: this,
    );
    _obscureText = widget.obscureText;

    _fadeAnimation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _animationController,
      curve: UIConstants.curveFast,
    ));

    _scaleAnimation = Tween<double>(
      begin: 0.95,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _animationController,
      curve: UIConstants.curveFast,
    ));
  }

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

  void _onFocusChange(bool hasFocus) {
    setState(() {
      _isFocused = hasFocus;
    });

    if (hasFocus) {
      _animationController.forward();
    } else {
      _animationController.reverse();
    }
  }

  void _onChanged(String value) {
    setState(() {
      _hasError = false;
    });

    if (widget.onChanged != null) {
      widget.onChanged!(value);
    }
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final colorScheme = theme.colorScheme;

    return AnimatedBuilder(
      animation: _animationController,
      builder: (context, child) {
        return Transform.scale(
          scale: _scaleAnimation.value,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              if (widget.label != null) ...[
                Padding(
                  padding: const EdgeInsets.only(bottom: UIConstants.spacing8),
                  child: Text(
                    widget.label!,
                    style: theme.textTheme.labelLarge?.copyWith(
                      color: _isFocused
                          ? colorScheme.primary
                          : colorScheme.onSurfaceVariant,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                ),
              ],
              Focus(
                onFocusChange: _onFocusChange,
                child: Container(
                  height: widget.height ?? UIConstants.inputHeightMedium,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(UIConstants.radius16),
                    color: _isFocused
                        ? colorScheme.surfaceVariant.withOpacity(0.5)
                        : colorScheme.surfaceVariant.withOpacity(0.3),
                    border: Border.all(
                      color: _hasError
                          ? colorScheme.error
                          : _isFocused
                              ? colorScheme.primary
                              : colorScheme.outline.withOpacity(0.3),
                      width: _isFocused ? 2.0 : 1.5,
                    ),
                    boxShadow: _isFocused
                        ? [
                            BoxShadow(
                              color: colorScheme.primary.withOpacity(0.1),
                              blurRadius: 8,
                              offset: const Offset(0, 2),
                            ),
                          ]
                        : null,
                  ),
                  child: TextFormField(
                    controller: widget.controller,
                    focusNode: widget.focusNode,
                    keyboardType: widget.keyboardType,
                    obscureText: _obscureText,
                    enabled: widget.enabled,
                    readOnly: widget.readOnly,
                    maxLines: widget.maxLines,
                    maxLength: widget.maxLength,
                    autofocus: widget.autofocus,
                    textCapitalization: widget.textCapitalization,
                    textInputAction: widget.textInputAction,
                    expands: widget.expands,
                    inputFormatters: widget.inputFormatters,
                    validator: (value) {
                      if (widget.validator != null) {
                        final result = widget.validator!(value);
                        setState(() {
                          _hasError = result != null;
                        });
                        return result;
                      }
                      return null;
                    },
                    onChanged: _onChanged,
                    onFieldSubmitted: widget.onSubmitted,
                    onTap: widget.onTap,
                    style: theme.textTheme.bodyLarge?.copyWith(
                      color: colorScheme.onSurface,
                    ),
                    decoration: InputDecoration(
                      hintText: widget.hint,
                      hintStyle: theme.textTheme.bodyMedium?.copyWith(
                        color: colorScheme.onSurfaceVariant.withOpacity(0.6),
                      ),
                      prefixIcon: widget.prefixIcon != null
                          ? Padding(
                              padding: const EdgeInsets.only(
                                  left: UIConstants.spacing16),
                              child: IconTheme(
                                data: IconThemeData(
                                  color: _isFocused
                                      ? colorScheme.primary
                                      : colorScheme.onSurfaceVariant,
                                  size: UIConstants.iconSizeMedium,
                                ),
                                child: widget.prefixIcon!,
                              ),
                            )
                          : null,
                      suffixIcon: (widget.suffixIcon != null)
                          ? Padding(
                              padding: const EdgeInsets.only(
                                  right: UIConstants.spacing16),
                              child: IconTheme(
                                data: IconThemeData(
                                  color: _isFocused
                                      ? colorScheme.primary
                                      : colorScheme.onSurfaceVariant,
                                  size: UIConstants.iconSizeMedium,
                                ),
                                child: widget.suffixIcon!,
                              ),
                            )
                          : (widget.obscureText
                              ? IconButton(
                                  onPressed: () {
                                    setState(() {
                                      _obscureText = !_obscureText;
                                    });
                                  },
                                  icon: Icon(
                                    _obscureText
                                        ? Icons.visibility_off_outlined
                                        : Icons.visibility_outlined,
                                  ),
                                )
                              : null),
                      border: InputBorder.none,
                      contentPadding: widget.contentPadding ??
                          const EdgeInsets.symmetric(
                            horizontal: UIConstants.spacing20,
                            vertical: UIConstants.spacing16,
                          ),
                      counterText: '',
                    ),
                  ),
                ),
              ),
              if (widget.helperText != null && !_hasError) ...[
                Padding(
                  padding: const EdgeInsets.only(top: UIConstants.spacing8),
                  child: Text(
                    widget.helperText!,
                    style: theme.textTheme.bodySmall?.copyWith(
                      color: colorScheme.onSurfaceVariant,
                    ),
                  ),
                ),
              ],
              if (widget.errorText != null && _hasError) ...[
                Padding(
                  padding: const EdgeInsets.only(top: UIConstants.spacing8),
                  child: Row(
                    children: [
                      Icon(
                        Icons.error_outline,
                        size: UIConstants.iconSizeSmall,
                        color: colorScheme.error,
                      ),
                      const SizedBox(width: UIConstants.spacing8),
                      Expanded(
                        child: Text(
                          widget.errorText!,
                          style: theme.textTheme.bodySmall?.copyWith(
                            color: colorScheme.error,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ],
          ),
        );
      },
    );
  }
}
