import 'dart:convert';

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/builders/dialogs.dart';

class MediaCard extends StatelessWidget {
  const MediaCard(
      {super.key, required this.media, this.callback, this.canDelete});

  final MediaItem media;
  final bool? canDelete;
  final Function? callback;

  @override
  Widget build(BuildContext context) {
    DecorationImage mediaImage(MediaItem media) {
      dynamic image;

      if (media.type == MediaType.image || media.type == MediaType.location) {
        image = NetworkImage(media.reference);
      } else if (media.type == MediaType.localImage) {
        image = Image.memory(base64Decode(media.reference)).image;
      } else if (media.type == MediaType.youtube) {
        image =
            NetworkImage('https://img.youtube.com/vi/${media.reference}/0.jpg');
      } else if (media.type == MediaType.localVideo) {}

      return DecorationImage(image: image, fit: BoxFit.cover);
    }

    return Container(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(10),
          image: mediaImage(media),
        ),
        child: Card(
            color: Colors.transparent,
            shape:
                RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
            shadowColor: const Color.fromARGB(0, 255, 255, 255),
            child: TextButton(
                onLongPress: () {
                  if (canDelete == true) {
                    showRemovalDialog(
                        'Media Removal',
                        'Would you like to permanently remove this media from the current session?',
                        context, () {
                      MediaItemsDao(
                              Provider.of<AppDatabase>(context, listen: false))
                          .remove(media);
                    }).then((result) {
                      if (callback != null) {
                        callback!();
                      }
                    });
                  }
                },
                onPressed: () => showMediaDetailWidget(context, media),
                child: const ListTile(
                  title: Text(''),
                ))));
  }
}
