import 'dart:developer';
import 'dart:io';

import 'package:better_open_file/better_open_file.dart';
import 'package:filesize/filesize.dart';
import 'package:flowder/flowder.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:jiffy/jiffy.dart';
import 'package:marianum_mobile/api/marianumcloud/webdav/queries/listFiles/cacheableFile.dart';
import 'package:path_provider/path_provider.dart';
import 'package:provider/provider.dart';

import '../../../api/marianumcloud/webdav/webdavApi.dart';
import '../../../data/files/filesProps.dart';

class FileElement extends StatefulWidget {
  CacheableFile file;
  Function updateAppBar;
  FileElement(this.file, this.updateAppBar, {Key? key}) : super(key: key);

  @override
  State<FileElement> createState() => _FileElementState();
}

class _FileElementState extends State<FileElement> {
  late DownloaderCore core;
  double percent = 0;

  void download(String remotePath, String name) async {

    Directory paths = await getApplicationDocumentsDirectory();

    String local = paths.path + Platform.pathSeparator + name;

    DownloaderUtils options = DownloaderUtils(
      progressCallback: (current, total) {
        final progress = (current / total) * 100;
        setState(() => {
          percent = progress,
        });
      },
      file: File(local),
      progress: ProgressImplementation(),
      deleteOnCancel: true,
      onDone: () {
        Future<OpenResult> result = OpenFile.open(local);

        result.then((value) => {
          if(value.type != ResultType.done) {
            showDialog(context: context, builder: (context) {
              return AlertDialog(
                title: Text("Download"),
                content: Text(value.message),
              );
            })
          }
        });

        widget.file.currentlyDownloading = false;
        percent = 0;
      },
    );

    log(local);

    core = await Flowder.download(
      "${await WebdavApi.webdavConnectString}$remotePath",
      options,
    );
  }

  Widget getSubtitle() {
    if(widget.file.currentlyDownloading) {
      return Row(
        children: [
          Container(
            margin: const EdgeInsets.only(right: 10),
            child: const Text("Download:"),
          ),
          Expanded(
            child: LinearProgressIndicator(value: percent/100),
          ),
          Container(
            margin: const EdgeInsets.only(left: 10),
            child: Text("${percent.round()}%"),
          ),
        ],
      );
    }
    return widget.file.isDirectory ? Text("geändert ${Jiffy(widget.file.modifiedAt).fromNow()}") : Text("${filesize(widget.file.size)}, ${Jiffy(widget.file.modifiedAt).fromNow()}");
  }

  @override
  Widget build(BuildContext context) {
    return ListTile(
      leading: Icon(widget.file.isDirectory ? Icons.folder : Icons.file_open_outlined),
      title: Text(widget.file.name),
      subtitle: getSubtitle(),
      trailing: Icon(widget.file.isDirectory ? Icons.arrow_right : Icons.open_in_browser),
      onTap: () {
        FilesProps props = Provider.of<FilesProps>(context, listen: false);
        widget.updateAppBar(props);
        if(widget.file.isDirectory) {
          props.enterFolder(widget.file.name);
        } else {
          setState(() {
            widget.file.currentlyDownloading = true;
          });

          download(widget.file.path, widget.file.name);

        }
      },
      onLongPress: () {
        showModalBottomSheet<void>(
          context: context,
          builder: (context) {
            return ListView(
              children: [
                ListTile(
                  leading: const Icon(Icons.delete),
                  title: Text("'${widget.file.name}' Löschen"),
                ),
                const ListTile(
                  leading: Icon(Icons.share),
                  title: Text("Teilen"),
                )
              ],
            );
          },
        );
      },
    );
  }
}