import 'package:aves/model/filters/covered/stored_album.dart';
import 'package:aves/model/filters/filters.dart';
import 'package:aves/model/source/collection_source.dart';
import 'package:aves/remote/remote_origin.dart';
import 'package:aves/widgets/common/grid/overlay.dart';
import 'package:aves/widgets/filter_grids/common/covered_filter_chip.dart';
import 'package:aves/widgets/filter_grids/common/overlay.dart';
import 'package:flutter/widgets.dart';
import 'package:provider/provider.dart';

enum _AlbumVisualKind {
  localOnly,
  remoteOnly,
  hybrid,
}

class FilterChipGridDecorator<T extends CollectionFilter, U extends FilterGridItem<T>> extends StatelessWidget {
  final U gridItem;
  final double extent;
  final bool selectable, highlightable;
  final Widget child;

  const FilterChipGridDecorator({
    super.key,
    required this.gridItem,
    required this.extent,
    this.selectable = true,
    this.highlightable = true,
    required this.child,
  });

  bool _isRemoteFolderPath(String path) {
    return path.startsWith('/photos/');
  }

  bool _isRemoteFolderStats(dynamic stats) {
    return stats.isRemote == RemoteOrigin.value || _isRemoteFolderPath(stats.path);
  }

  String _albumKey(String path) {
    final normalized = path.replaceAll('\\', '/');
    final parts = normalized.split('/').where((s) => s.isNotEmpty).toList();
    return parts.isEmpty ? path : parts.last;
  }

  _AlbumVisualKind _albumVisualKind(CollectionSource source) {
    final filter = gridItem.filter;

    if (filter is! StoredAlbumFilter) {
      return _AlbumVisualKind.remoteOnly;
    }

    final albumPath = filter.album;
    final stats = source.folderMap[albumPath];

    if (stats == null) {
      return _AlbumVisualKind.localOnly;
    }

    if (stats.hybridType != null) {
      return _AlbumVisualKind.hybrid;
    }

    final key = _albumKey(albumPath);

    final matchingFolders = source.folderMap.values.where(
      (f) => _albumKey(f.path) == key,
    );

    final hasRemote = matchingFolders.any(_isRemoteFolderStats);
    final hasLocal = matchingFolders.any((f) => !_isRemoteFolderStats(f));

    if (hasRemote && hasLocal) {
      return _AlbumVisualKind.hybrid;
    }

    if (_isRemoteFolderStats(stats)) {
      return _AlbumVisualKind.remoteOnly;
    }

    return _AlbumVisualKind.localOnly;
  }

  BorderRadius _borderRadius(BuildContext context) {
    final source = context.read<CollectionSource>();
    final visualKind = _albumVisualKind(source);

    switch (visualKind) {
      case _AlbumVisualKind.localOnly:
        // Album locale: squadrato.
        return BorderRadius.zero;

      case _AlbumVisualKind.remoteOnly:
        // Album remoto: arrotondato come Aves originale.
        return BorderRadius.all(CoveredFilterChip.radius(extent));

      case _AlbumVisualKind.hybrid:
        // Album locale + remoto: cornice esterna squadrata.
        // La cover interna arrotondata viene gestita in CoveredFilterChip.
        return BorderRadius.zero;
    }
  }

  @override
  Widget build(BuildContext context) {
    final borderRadius = _borderRadius(context);

    return SizedBox(
      width: extent,
      height: extent,
      child: Stack(
        fit: StackFit.passthrough,
        children: [
          child,
          if (selectable)
            GridItemSelectionOverlay<FilterGridItem<T>>(
              item: gridItem,
              borderRadius: borderRadius,
              padding: EdgeInsets.all(extent / 24),
            ),
          if (highlightable)
            ChipHighlightOverlay(
              filter: gridItem.filter,
              extent: extent,
              borderRadius: borderRadius,
            ),
        ],
      ),
    );
  }
}
