import 'package:flutter/material.dart';
//import 'package:aves/database/local_media_db.dart';
import 'package:aves/model/entry/entry.dart';
//import 'package:aves/utils/file_utils.dart';
import 'package:aves/services/common/services.dart';

class FolderPickerPage extends StatefulWidget {
  static const routeName = '/folder_picker';

  const FolderPickerPage({super.key});

  @override
  State<FolderPickerPage> createState() => _FolderPickerPageState();
}

class _FolderPickerPageState extends State<FolderPickerPage> {
  late Future<List<_FolderRow>> _future;

  @override
  void initState() {
    super.initState();
    _future = _loadFolders();
  }

  Future<List<_FolderRow>> _loadFolders() async {
    final rows = await localMediaDb.loadAllFolders();
    final entries = await localMediaDb.loadEntriesMap();

    final list = <_FolderRow>[];

    for (final row in rows) {
      final thumbEntry = row.thumbEntryId != null ? entries[row.thumbEntryId] : null;

      list.add(
        _FolderRow(
          path: row.path,
          displayName: row.displayName,
          albumType: row.albumType,
          priority: row.priority,
          totalSize: row.totalSize,
          fileCount: row.fileCount,
          isRemote: row.isRemote == 1,
          hybridType: row.hybridType,
          thumbEntry: thumbEntry,
        ),
      );
    }

    return _sortFolders(list);
  }

  List<_FolderRow> _sortFolders(List<_FolderRow> folders) {
    folders.sort((a, b) {
      final p = b.priority.compareTo(a.priority);
      if (p != 0) return p;

      if (a.albumType == 3 && b.albumType != 3) return -1;
      if (b.albumType == 3 && a.albumType != 3) return 1;

      if (a.isRemote != b.isRemote) {
        return a.isRemote ? 1 : -1;
      }

      return a.displayName.toLowerCase().compareTo(b.displayName.toLowerCase());
    });

    return folders;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Scegli cartella')),
      body: FutureBuilder<List<_FolderRow>>(
        future: _future,
        builder: (context, snapshot) {
          if (!snapshot.hasData) {
            return const Center(child: CircularProgressIndicator());
          }

          final folders = snapshot.data!;
          if (folders.isEmpty) {
            return const Center(child: Text('Nessuna cartella'));
          }

          return ListView.builder(
            itemCount: folders.length,
            itemBuilder: (context, index) {
              return _FolderTile(
                folder: folders[index],
                onTap: () => Navigator.pop(context, folders[index].path),
              );
            },
          );
        },
      ),
    );
  }
}

class _FolderRow {
  final String path;
  final String displayName;
  final int albumType;
  final int priority;
  final int totalSize;
  final int fileCount;
  final bool isRemote;
  final int hybridType;
  final AvesEntry? thumbEntry;

  _FolderRow({
    required this.path,
    required this.displayName,
    required this.albumType,
    required this.priority,
    required this.totalSize,
    required this.fileCount,
    required this.isRemote,
    required this.hybridType,
    required this.thumbEntry,
  });
}

class _FolderTile extends StatelessWidget {
  final _FolderRow folder;
  final VoidCallback onTap;

  const _FolderTile({
    required this.folder,
    required this.onTap,
  });

  @override
  Widget build(BuildContext context) {
    final thumb = folder.thumbEntry;

    return ListTile(
      leading: ClipRRect(
        borderRadius: BorderRadius.circular(6),
        child: SizedBox(
          width: 56,
          height: 56,
          child: thumb != null
              ? Image(
                  image: thumb.thumbnailProvider(),
                  fit: BoxFit.cover,
                )
              : Container(
                  color: Colors.grey.shade300,
                  child: const Icon(Icons.folder, size: 32, color: Colors.black54),
                ),
        ),
      ),
      title: Text(folder.displayName),
      subtitle: Text(
        '${folder.fileCount} elementi • ${_formatSize(folder.totalSize)}',
      ),
      trailing: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          if (folder.isRemote)
            const Icon(Icons.cloud, size: 18),
          if (folder.albumType == 3)
            const Icon(Icons.lock, size: 18),
          if (folder.hybridType != 0)
            const Icon(Icons.link, size: 18),
        ],
      ),
      onTap: onTap,
    );
  }

  String _formatSize(int bytes) {
    if (bytes < 1024) return '$bytes B';
    if (bytes < 1024 * 1024) return '${(bytes / 1024).toStringAsFixed(1)} KB';
    if (bytes < 1024 * 1024 * 1024) return '${(bytes / 1024 / 1024).toStringAsFixed(1)} MB';
    return '${(bytes / 1024 / 1024 / 1024).toStringAsFixed(1)} GB';
  }
}
