import 'dart:async';
import 'package:flutter/material.dart';
import 'package:aves/model/entry/entry.dart';
import 'package:aves/services/common/services.dart';
import 'package:aves/widgets/dialogs/aves_confirmation_dialog.dart';

/// Funzioni di utilità per le azioni sugli entry.
/// Versione ultra‑ottimizzata, senza album, senza grouping, senza filter_grids.
class EntryActionUtils {
  // ------------------------------------------------------------
  // COPY
  // ------------------------------------------------------------

  static Future<void> copyEntries(
    BuildContext context,
    List<AvesEntry> entries,
  ) async {
    if (entries.isEmpty) return;

    final targetDir = await _pickTargetDirectory(context);
    if (targetDir == null) return;

    for (final entry in entries) {
      try {
        await mediaEditService.copyEntry(entry, targetDir);
      } catch (e) {
        _show(context, 'Errore copia: $e');
      }
    }

    _show(context, 'Copia completata');
  }

  // ------------------------------------------------------------
  // MOVE
  // ------------------------------------------------------------

  static Future<void> moveEntries(
    BuildContext context,
    List<AvesEntry> entries,
  ) async {
    if (entries.isEmpty) return;

    final targetDir = await _pickTargetDirectory(context);
    if (targetDir == null) return;

    for (final entry in entries) {
      try {
        await mediaEditService.moveEntry(entry, targetDir);
      } catch (e) {
        _show(context, 'Errore spostamento: $e');
      }
    }

    _show(context, 'Spostamento completato');
  }

  // ------------------------------------------------------------
  // DIRECTORY PICKER (semplice e moderno)
  // ------------------------------------------------------------

  static Future<String?> _pickTargetDirectory(BuildContext context) async {
    try {
      final dir = await appService.pickDirectory();
      return dir;
    } catch (e) {
      _show(context, 'Errore selezione cartella: $e');
      return null;
    }
  }

  // ------------------------------------------------------------
  // DELETE CONFIRMATION (usato anche da altri handler)
  // ------------------------------------------------------------

  static Future<bool> confirmDelete(
    BuildContext context,
    int count,
  ) async {
    final result = await showDialog<bool>(
      context: context,
      builder: (_) => AvesConfirmationDialog(
        title: 'Elimina',
        message: 'Vuoi eliminare $count elementi?',
      ),
    );
    return result == true;
  }

  // ------------------------------------------------------------
  // UTILS
  // ------------------------------------------------------------

  static void _show(BuildContext context, String msg) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text(msg)),
    );
  }
}
