import 'package:flutter/material.dart';

import '../../../../state/app/modules/files/bloc/files_bloc.dart';
import '../../../../widget/demo_restricted.dart';
import '../../../../widget/details_bottom_sheet.dart';
import '../../../../widget/file_pick.dart';
import '../../../../widget/prompt_dialog.dart';

/// Opens the "Element hinzufügen" sheet (create folder, upload, take photo, …).
/// [onPickedFiles] receives selected/captured file paths (gallery, file picker
/// or camera) and is responsible for kicking off the upload flow.
void showAddFileSheet(
  BuildContext context, {
  required FilesBloc bloc,
  required Future<void> Function(List<String>? paths) onPickedFiles,
}) {
  if (guardDemoAction(context)) return;
  showDetailsBottomSheet(
    context,
    children: (sheetCtx) => [
      ListTile(
        leading: const Icon(Icons.create_new_folder_outlined),
        title: const Text('Ordner erstellen'),
        onTap: () {
          Navigator.of(sheetCtx).pop();
          showCreateFolderDialog(context, bloc);
        },
      ),
      ListTile(
        leading: const Icon(Icons.upload_file),
        title: const Text('Aus Dateien hochladen'),
        onTap: () {
          FilePick.documentPick().then(onPickedFiles);
          Navigator.of(sheetCtx).pop();
        },
      ),
      ListTile(
        leading: const Icon(Icons.add_a_photo_outlined),
        title: const Text('Aus Galerie hochladen'),
        onTap: () {
          FilePick.multipleGalleryPick().then((value) {
            if (value != null) onPickedFiles(value.map((e) => e.path).toList());
          });
          Navigator.of(sheetCtx).pop();
        },
      ),
      ListTile(
        leading: const Icon(Icons.camera_alt_outlined),
        title: const Text('Foto aufnehmen'),
        onTap: () {
          FilePick.cameraPick().then((image) {
            if (image != null) onPickedFiles([image.path]);
          });
          Navigator.of(sheetCtx).pop();
        },
      ),
    ],
  );
}

void showCreateFolderDialog(BuildContext context, FilesBloc bloc) {
  showPromptDialog(
    context,
    title: 'Neuer Ordner',
    confirmButton: 'Ordner erstellen',
    onConfirm: (name) async {
      if (name.isEmpty) {
        throw Exception('Bitte einen Namen eingeben.');
      }
      await bloc.createFolder(name);
    },
  );
}
