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

import '../../../api/marianumcloud/files-sharing/fileSharingApi.dart';
import '../../../api/marianumcloud/files-sharing/fileSharingApiParams.dart';
import '../../../api/marianumcloud/talk/sendMessage/sendMessage.dart';
import '../../../api/marianumcloud/talk/sendMessage/sendMessageParams.dart';
import '../../../model/chatList/chatProps.dart';
import '../../../widget/filePick.dart';
import '../files/fileUploadDialog.dart';

class ChatTextfield extends StatefulWidget {
  final String sendToToken;
  const 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;
  bool isLoading = false;

  void _query() {
    Provider.of<ChatProps>(context, listen: false).run();
  }

  void mediaUpload(String? path) async {
    context.loaderOverlay.hide();

    if(path == null) {
      return;
    }

    String filename = "${path.split("/").last.split(".").first}-${const Uuid().v4()}.${path.split(".").last}";
    String shareFolder = "MarianumMobile";
    showDialog(context: context, builder: (context) => FileUploadDialog(
      doShowFinish: false,
      fileName: filename,
      localPath: path,
      remotePath: [shareFolder],
      onUploadFinished: () {
        FileSharingApi().share(FileSharingApiParams(
            shareType: 10,
            shareWith: widget.sendToToken,
            path: "$shareFolder/$filename",
        )).then((value) => _query());
      },
    ), barrierDismissible: false);
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        Align(
          alignment: Alignment.bottomLeft,
          child: Container(
            padding: const EdgeInsets.only(left: 10, bottom: 1, top: 1, right: 10),
            width: double.infinity,
            color: Theme.of(context).colorScheme.secondary,
            child: Row(
              children: <Widget>[
                GestureDetector(
                  onTap: (){
                    showDialog(context: context, builder: (context) {
                      return SimpleDialog(
                        children: [
                          ListTile(
                            leading: const Icon(Icons.file_open),
                            title: const Text("Aus Dateien auswählen"),
                            onTap: () {
                              context.loaderOverlay.show();
                              FilePick.documentPick().then((value) {
                                mediaUpload(value);
                              });
                              Navigator.of(context).pop();
                            },
                          ),
                          ListTile(
                            leading: const Icon(Icons.image),
                            title: const Text("Aus Gallerie auswählen"),
                            onTap: () {
                              context.loaderOverlay.show();
                              FilePick.galleryPick().then((value) {
                                mediaUpload(value?.path);
                              });
                              Navigator.of(context).pop();
                            },
                          ),
                        ],
                      );
                    });
                  },
                  child: Container(
                    height: 30,
                    width: 30,
                    decoration: BoxDecoration(
                      color: Theme.of(context).primaryColor,
                      borderRadius: BorderRadius.circular(30),
                    ),
                    child: const Icon(Icons.add, color: Colors.white, size: 20, ),
                  ),
                ),
                const SizedBox(width: 15),
                Expanded(
                  child: TextField(
                    controller: _textBoxController,
                    readOnly: sending,
                    maxLines: 7,
                    minLines: 1,
                    decoration: InputDecoration(
                        hintText: "Nachricht schreiben...",
                        hintStyle: TextStyle(color: Theme.of(context).colorScheme.onSecondary),
                        border: InputBorder.none
                    ),
                  ),
                ),
                const SizedBox(width: 15),
                FloatingActionButton(
                  mini: true,
                  onPressed: (){
                    if(_textBoxController.text.isEmpty) return;
                    setState(() {
                      sending = true;
                    });
                    SendMessage(widget.sendToToken, SendMessageParams(_textBoxController.text)).run().then((value) => {
                      _query(),
                      _textBoxController.text = "",
                      setState(() {
                        sending = false;
                      }),
                    });
                  },
                  backgroundColor: Theme.of(context).primaryColor,
                  elevation: 0,
                  child: const Icon(Icons.send, color: Colors.white, size: 18),
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }
}