import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:kasy_kit/components/components.dart';
import 'package:kasy_kit/core/theme/theme.dart';
import 'package:kasy_kit/i18n/translations.g.dart';

/// Maximum characters allowed in a single chat message.
const int kLlmChatMaxMessageLength = 2000;

/// Unified chat bar: primary [KasyTextField] shell (surface, border, shadow) + send orb inside.
class LlmChatComposer extends StatefulWidget {
  const LlmChatComposer({
    super.key,
    required this.controller,
    required this.onSend,
    required this.isReplying,
  });

  final TextEditingController controller;
  final VoidCallback onSend;
  final bool isReplying;

  static const int _maxLines = 5;

  @override
  State<LlmChatComposer> createState() => _LlmChatComposerState();
}

class _LlmChatComposerState extends State<LlmChatComposer> {
  bool _canSend = false;

  @override
  void initState() {
    super.initState();
    _canSend = _hasSendableText(widget.controller.text);
    widget.controller.addListener(_onTextChanged);
  }

  @override
  void dispose() {
    widget.controller.removeListener(_onTextChanged);
    super.dispose();
  }

  bool _hasSendableText(String value) {
    final String trimmed = value.trim();
    return trimmed.isNotEmpty && trimmed.length <= kLlmChatMaxMessageLength;
  }

  void _onTextChanged() {
    final bool nextCanSend = _hasSendableText(widget.controller.text);
    if (nextCanSend == _canSend) return;
    setState(() => _canSend = nextCanSend);
  }

  void _handleSend() {
    if (!_canSend || widget.isReplying) return;
    widget.onSend();
    setState(() => _canSend = false);
  }

  @override
  Widget build(BuildContext context) {
    final bool enabled = !widget.isReplying;
    final BorderRadius shellRadius = BorderRadius.circular(22);
    final Color borderColor = KasyShadows.inputFieldRestingBorder(context);

    return DecoratedBox(
      decoration: BoxDecoration(
        color: context.colors.surface,
        borderRadius: shellRadius,
        border: Border.all(color: borderColor),
        boxShadow: kIsWeb
            ? null
            : [KasyShadows.inputField(context, enabled: enabled)],
      ),
      child: Padding(
        padding: const EdgeInsets.fromLTRB(
          KasySpacing.md,
          KasySpacing.xs,
          KasySpacing.sm,
          KasySpacing.xs,
        ),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.end,
          children: [
            Expanded(
              child: KasyTextField(
                controller: widget.controller,
                enabled: enabled,
                variant: KasyTextFieldVariant.embedded,
                hint: t.llm_chat.hint,
                minLines: 1,
                maxLines: LlmChatComposer._maxLines,
                textCapitalization: TextCapitalization.sentences,
                textInputAction: TextInputAction.newline,
                inputFormatters: [
                  LengthLimitingTextInputFormatter(kLlmChatMaxMessageLength),
                ],
                onSubmitted: (_) => _handleSend(),
              ),
            ),
            if (_canSend || widget.isReplying) ...[
              const SizedBox(width: KasySpacing.xs),
              Padding(
                padding: const EdgeInsets.only(bottom: 2),
                child: KasyButton.iconOnly(
                  icon: KasyIcons.arrowUp,
                  isLoading: widget.isReplying,
                  onPressed: _canSend && !widget.isReplying ? _handleSend : null,
                  size: KasyButtonSize.small,
                  iconOnlyLayoutExtent: 36,
                  iconGlyphSize: 18,
                  semanticLabel: t.llm_chat.hint,
                ),
              ),
            ],
          ],
        ),
      ),
    );
  }
}
