
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:loader_overlay/loader_overlay.dart';
import 'package:nextcloud/nextcloud.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 '../../../../api/marianumcloud/webdav/webdavApi.dart';
import '../../../../model/chatList/chatProps.dart';
import '../../../../storage/base/settingsProvider.dart';
import '../../../../widget/filePick.dart';
import '../../files/fileUploadDialog.dart';

class ChatTextfield extends StatefulWidget {
  final String sendToToken;
  const ChatTextfield(this.sendToToken, {super.key});

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

class _ChatTextfieldState extends State<ChatTextfield> {
  late SettingsProvider settings;
  final TextEditingController _textBoxController = TextEditingController();
  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";
    WebdavApi.webdav.then((webdav) {
      webdav.mkcol(PathUri.parse("/$shareFolder"));
    });

    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);
  }

  void setDraft(String text) {
    if(text.isNotEmpty) {
      settings.val(write: true).talkSettings.drafts[widget.sendToToken] = text;
    } else {
      settings.val(write: true).talkSettings.drafts.removeWhere((key, value) => key == widget.sendToToken);
    }
  }

  @override
  void initState() {
    super.initState();
    settings = Provider.of<SettingsProvider>(context, listen: false);
  }

  @override
  Widget build(BuildContext context) {
    _textBoxController.text = settings.val().talkSettings.drafts[widget.sendToToken] ?? "";

    return Stack(
      children: <Widget>[
        Align(
          alignment: Alignment.bottomLeft,
          child: Container(
            padding: const EdgeInsets.only(left: 10, bottom: 3, top: 3, right: 10),
            width: double.infinity,
            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();
                            },
                          ),
                          Visibility(
                            visible: !Platform.isIOS,
                            child: 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: Material(
                    elevation: 5,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(30),
                    ),
                    child: Container(
                      height: 30,
                      width: 30,
                      decoration: BoxDecoration(
                        color: Theme.of(context).primaryColor,
                        borderRadius: BorderRadius.circular(30),
                      ),
                      child: const Icon(Icons.attach_file_outlined, color: Colors.white, size: 20, ),
                    ),
                  )
                ),
                const SizedBox(width: 15),
                Expanded(
                  child: TextField(
                    autocorrect: true,
                    textCapitalization: TextCapitalization.sentences,
                    controller: _textBoxController,
                    maxLines: 7,
                    minLines: 1,
                    decoration: const InputDecoration(
                      hintText: "Nachricht schreiben...",
                      border: InputBorder.none,
                    ),
                    onChanged: (String text) {
                      if(text.trim().toLowerCase() == "marbot marbot marbot") {
                        var newText = "Roboter sind cool und so, aber Marbots sind besser!";
                        _textBoxController.text = newText;
                        text = newText;
                      }
                      setDraft(text);
                    },
                  ),
                ),
                const SizedBox(width: 15),
                FloatingActionButton(
                  mini: true,
                  onPressed: (){
                    if(_textBoxController.text.isEmpty) return;
                    if(isLoading) return;

                    setState(() {
                      isLoading = true;
                    });
                    SendMessage(widget.sendToToken, SendMessageParams(_textBoxController.text)).run().then((value) {
                      _query();
                      setState(() {
                        isLoading = false;
                      });
                      _textBoxController.text = "";
                      setDraft("");
                    });
                  },
                  backgroundColor: Theme.of(context).primaryColor,
                  elevation: 5,
                  child: isLoading
                      ? Container(padding: const EdgeInsets.all(10), child: const CircularProgressIndicator(color: Colors.white, strokeWidth: 2))
                      : const Icon(Icons.send, color: Colors.white, size: 18),
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }
}
