import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:sendtrain/daos/media_items_dao.dart';
import 'package:sendtrain/database/database.dart';
import 'package:sendtrain/helpers/widget_helpers.dart';
import 'package:sendtrain/widgets/media/media_card.dart';
import 'package:sendtrain/widgets/sessions/session_editor.dart';

class SessionViewMedia extends StatefulWidget {
  const SessionViewMedia({super.key, required this.session});

  final Session session;

  @override
  State<SessionViewMedia> createState() => _SessionViewMediaState();
}

class _SessionViewMediaState extends State<SessionViewMedia> {
  void resetState() {
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<List<MediaItem>>(
        future: MediaItemsDao(Provider.of<AppDatabase>(context))
            .fromSession(widget.session.id),
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            final mediaItems = snapshot.data!;

            List<Widget> content;
            if (mediaItems.isNotEmpty) {
              List<Widget> mediaCards = List.generate(mediaItems.length,
                  (i) => MediaCard(media: mediaItems[i], callback: resetState, canDelete: true));
              content = mediaCards;
            } else {
              content = [
                FloatingActionButton(
                    onPressed: () {
                      showEditorSheet(
                          context,
                          SessionEditor(
                              session: widget.session, callback: resetState));
                    },
                    mini: true,
                    child: Icon(Icons.add_a_photo_rounded))
              ];
            }

            return Column(
              children: [
                SizedBox(
                    width: double.infinity,
                    height: 100,
                    child: GridView.count(
                        padding: const EdgeInsets.fromLTRB(15, 0, 0, 0),
                        scrollDirection: Axis.horizontal,
                        crossAxisSpacing: 5,
                        mainAxisSpacing: 5,
                        crossAxisCount: 1,
                        children: content))
              ],
            );
          } else {
            return Padding(
                padding: EdgeInsets.all(15),
                child: CircularProgressIndicator());
          }
        });
  }
}
