import 'package:flutter/material.dart';
import 'package:flutter_lucide/flutter_lucide.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../../../playlists/playlists_provider.dart';
import '../../../theme/theme_extension.dart';

/// Modal bottom sheet listing the caller's user-created playlists.
/// Returns the picked playlistId via Navigator.pop, or null on cancel.
class AddToPlaylistSheet extends ConsumerWidget {
  const AddToPlaylistSheet({super.key});

  static Future<String?> show(BuildContext context) {
    return showModalBottomSheet<String>(
      context: context,
      isScrollControlled: true,
      builder: (_) => const AddToPlaylistSheet(),
    );
  }

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final fs = Theme.of(context).extension<FabledSwordTheme>()!;
    final lists = ref.watch(playlistsListProvider('user'));
    return SafeArea(
      child: Container(
        color: fs.iron,
        padding: const EdgeInsets.symmetric(vertical: 8),
        constraints: BoxConstraints(
          maxHeight: MediaQuery.of(context).size.height * 0.6,
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Padding(
              padding: const EdgeInsets.fromLTRB(20, 8, 20, 8),
              child: Text(
                'Add to playlist',
                style: TextStyle(
                  color: fs.parchment,
                  fontFamily: 'Fraunces',
                  fontSize: 20,
                ),
              ),
            ),
            Flexible(
              child: lists.when(
                loading: () => const Center(child: CircularProgressIndicator()),
                error: (e, _) => Padding(
                  padding: const EdgeInsets.all(16),
                  child: Text('$e', style: TextStyle(color: fs.error)),
                ),
                data: (data) {
                  final owned = data.owned
                      .where((p) => p.systemVariant == null)
                      .toList();
                  if (owned.isEmpty) {
                    return Padding(
                      padding: const EdgeInsets.all(20),
                      child: Text(
                        "You haven't created any playlists yet.",
                        style: TextStyle(color: fs.ash),
                      ),
                    );
                  }
                  return ListView.builder(
                    shrinkWrap: true,
                    itemCount: owned.length,
                    itemBuilder: (_, i) {
                      final p = owned[i];
                      // Material(transparency) gives ListTile an ink target
                      // beneath the outer Container's color paint — required
                      // by the Flutter 3.44 ListTile/ColoredBox assertion.
                      return Material(
                        type: MaterialType.transparency,
                        child: ListTile(
                          key: Key('add_to_playlist_${p.id}'),
                          leading: Icon(LucideIcons.list_music, color: fs.parchment),
                          title: Text(
                            p.name,
                            style: TextStyle(color: fs.parchment),
                          ),
                          subtitle: Text(
                            '${p.trackCount} ${p.trackCount == 1 ? "track" : "tracks"}',
                            style: TextStyle(color: fs.ash, fontSize: 12),
                          ),
                          onTap: () => Navigator.pop(context, p.id),
                        ),
                      );
                    },
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}
