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

import '../../../../api/marianumcloud/webdav/queries/list_files/cacheable_file.dart';
import '../../../../extensions/date_time.dart';
import '../../../../utils/clipboard_helper.dart';
import '../../../../widget/details_bottom_sheet.dart';
import 'file_leading.dart';

/// Shows a modal bottom sheet with technical metadata about a single file or
/// folder: full path, MIME type, size, timestamps, ETag.
void showFileDetailsSheet(BuildContext context, CacheableFile file) {
  showDetailsBottomSheet(
    context,
    header: ListTile(
      leading: FileLeading(file: file, size: 40),
      title: Text(
        file.name,
        style: const TextStyle(fontWeight: FontWeight.bold),
      ),
      subtitle: Text(file.isDirectory ? 'Ordner' : (file.mimeType ?? '–')),
    ),
    children: (_) => [
      _DetailRow(label: 'Pfad', value: file.path, copyable: true),
      if (!file.isDirectory)
        _DetailRow(label: 'Größe', value: filesize(file.size)),
      if (file.modifiedAt != null)
        _DetailRow(
          label: 'Geändert',
          value:
              '${file.modifiedAt!.formatDateTime()} (${file.modifiedAt!.formatRelative()})',
        ),
      if (file.createdAt != null)
        _DetailRow(label: 'Erstellt', value: file.createdAt!.formatDateTime()),
      if (file.eTag != null)
        _DetailRow(label: 'ETag', value: file.eTag!, copyable: true),
    ],
  );
}

class _DetailRow extends StatelessWidget {
  const _DetailRow({
    required this.label,
    required this.value,
    this.copyable = false,
  });
  final String label;
  final String value;
  final bool copyable;

  @override
  Widget build(BuildContext context) => Padding(
    padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 6),
    child: Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        SizedBox(
          width: 90,
          child: Text(
            label,
            style: TextStyle(
              color: Theme.of(context).colorScheme.onSurfaceVariant,
            ),
          ),
        ),
        Expanded(child: SelectableText(value)),
        if (copyable)
          IconButton(
            tooltip: 'Kopieren',
            icon: const Icon(Icons.copy, size: 18),
            onPressed: () => copyToClipboard(context, value),
          ),
      ],
    ),
  );
}
