import 'package:flutter/material.dart';
import 'package:syncrow_web/utils/color_manager.dart';

class SubspaceNameDisplayWidget extends StatefulWidget {
  final String text;
  final TextStyle? textStyle;
  final Color backgroundColor;
  final Color borderColor;
  final EdgeInsetsGeometry padding;
  final BorderRadiusGeometry borderRadius;
  final void Function(String updatedName) onNameChanged;
  final bool Function(String updatedName) validateName;

  const SubspaceNameDisplayWidget({
    Key? key,
    required this.text,
    this.textStyle,
    this.backgroundColor = ColorsManager.whiteColors,
    this.borderColor = ColorsManager.transparentColor,
    this.padding = const EdgeInsets.symmetric(horizontal: 8.0, vertical: 4.0),
    this.borderRadius = const BorderRadius.all(Radius.circular(10)),
    required this.onNameChanged,
    required this.validateName,
  }) : super(key: key);

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

class _SubspaceNameDisplayWidgetState extends State<SubspaceNameDisplayWidget> {
  bool isEditing = false;
  late TextEditingController _controller;
  late FocusNode _focusNode;
  late String previousName;
  String? errorText;

  @override
  void initState() {
    super.initState();
    _controller = TextEditingController(text: widget.text);
    _focusNode = FocusNode();
    previousName = widget.text;
  }

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

  void _handleValidationAndSave() {
    final updatedName = _controller.text;

    if (updatedName.isEmpty) {
      setState(() {
        errorText = 'Subspace name cannot be empty.';
      });
      return;
    }
    if (widget.validateName(updatedName)) {
      setState(() {
        errorText = null;
        isEditing = false;
        previousName = updatedName;
        widget.onNameChanged(updatedName);
      });
    } else {
      setState(() {
        errorText = 'Subspace name already exists.';
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        GestureDetector(
          onTap: () {
            setState(() {
              isEditing = true;
              _focusNode.requestFocus();
            });
          },
          child: Container(
            padding: widget.padding,
            decoration: BoxDecoration(
              color: widget.backgroundColor,
              borderRadius: widget.borderRadius,
              border: Border.all(color: widget.borderColor),
            ),
            child: isEditing
                ? TextField(
                    controller: _controller,
                    focusNode: _focusNode,
                    style: widget.textStyle ??
                        Theme.of(context)
                            .textTheme
                            .bodySmall
                            ?.copyWith(color: ColorsManager.spaceColor),
                    autofocus: true,
                    decoration: const InputDecoration(
                      border: InputBorder.none,
                      contentPadding: EdgeInsets.symmetric(horizontal: 8.0),
                    ),
                    onSubmitted: (value) {
                      _handleValidationAndSave();
                    },
                  )
                : Text(
                    widget.text,
                    style: widget.textStyle ??
                        Theme.of(context)
                            .textTheme
                            .bodySmall
                            ?.copyWith(color: ColorsManager.spaceColor),
                  ),
          ),
        ),
        if (errorText != null)
          Padding(
            padding: const EdgeInsets.only(top: 4.0),
            child: Text(
              errorText!,
              style: Theme.of(context)
                  .textTheme
                  .bodyMedium!
                  .copyWith(color: ColorsManager.warningRed),
            ),
          ),
      ],
    );
  }
}
