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

import '../../../api/marianumcloud/talk/sendMessage/sendMessage.dart';
import '../../../api/marianumcloud/talk/sendMessage/sendMessageParams.dart';
import '../../../data/chatList/chatProps.dart';

class ChatTextfield extends StatefulWidget {
  String sendToToken;
  ChatTextfield(this.sendToToken, {Key? key}) : super(key: key);

  @override
  State<ChatTextfield> createState() => _ChatTextfieldState();
}

class _ChatTextfieldState extends State<ChatTextfield> {
  final TextEditingController _textBoxController = TextEditingController();
  bool sending = false;

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Theme.of(context).dividerColor,
      padding: const EdgeInsets.all(10),
      child: Row(
        children: [
          Expanded(
            child: TextField(
              controller: _textBoxController,
              readOnly: sending,
              maxLines: null,
              decoration: const InputDecoration(
                hintText: "Nachricht",
                border: OutlineInputBorder(),
                labelText: "",
              ),
            ),
          ),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 15),
            child: sending ? const Center(child: CircularProgressIndicator()) : IconButton(
                onPressed: () {
                  if(_textBoxController.text.isEmpty) return;
                  setState(() {
                    sending = true;
                  });
                  SendMessage(widget.sendToToken, SendMessageParams(_textBoxController.text)).run().then((value) => {
                    Provider.of<ChatProps>(context, listen: false).run(),
                    _textBoxController.text = "",
                    setState(() {
                      sending = false;
                    }),
                  });
                },
                icon: const Icon(Icons.send)
            ),
          )
        ],
      ),
    );
  }
}