import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:sendtrain/daos/media_items_dao.dart';
import 'package:sendtrain/daos/session_activities_dao.dart';
import 'package:sendtrain/database/database.dart';
import 'package:sendtrain/extensions/string_extensions.dart';
import 'package:sendtrain/helpers/date_time_helpers.dart';
import 'package:sendtrain/helpers/media_helpers.dart';
import 'package:sendtrain/helpers/widget_helpers.dart';
import 'package:sendtrain/models/activity_timer_model.dart';
import 'package:sendtrain/widgets/activities/activity_view.dart';
import 'package:sendtrain/widgets/builders/dialogs.dart';
import 'package:sendtrain/widgets/generic/elements/card_image.dart';
import 'package:sendtrain/widgets/generic/elements/generic_progress_indicator.dart';

class ActivityCard extends StatefulWidget {
  final Activity activity;
  final Session session;
  final Function? callback;

  const ActivityCard(
      {super.key,
      required this.activity,
      required this.session,
      this.callback});

  @override
  State<ActivityCard> createState() => ActivityCardState();
}

class ActivityCardState extends State<ActivityCard> {
  @override
  Widget build(BuildContext context) {
    final ActivityTimerModel atm = Provider.of<ActivityTimerModel>(context);

    return FutureBuilder<List<MediaItem>>(
        future: MediaItemsDao(Provider.of<AppDatabase>(context))
            .fromActivity(widget.activity),
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            List<MediaItem> mediaItems = snapshot.data!;

            return Card.outlined(
              color: atm.activity?.id == widget.activity.id
                  ? Theme.of(context).colorScheme.primaryContainer
                  : Theme.of(context).colorScheme.surfaceContainerLow,
              clipBehavior: Clip.hardEdge,
              child: InkWell(
                  onTap: () => showGenericDialog(
                      ActivityView(session: widget.session, activity: widget.activity), context),
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: <Widget>[
                      ListTile(
                          leading: CardImage(
                              image:
                                  findMediaByType(mediaItems, MediaType.image)),
                          title: Consumer<ActivityTimerModel>(
                            builder: (context, atm, child) {
                              if (atm.activity?.id == widget.activity.id) {
                                return Text(
                                    maxLines: 1,
                                    overflow: TextOverflow.ellipsis,
                                    "${widget.activity.title.toTitleCase()} (${formattedTime(atm.totalTime)})");
                              } else {
                                return Text(
                                    maxLines: 1,
                                    overflow: TextOverflow.ellipsis,
                                    widget.activity.title.toTitleCase());
                              }
                            },
                          ),
                          subtitle: Text(
                              overflow: TextOverflow.ellipsis,
                              maxLines: 2,
                              softWrap: true,
                              jsonToDescription(json
                                  .decode(widget.activity.description ?? ""))),
                          contentPadding: EdgeInsets.only(left: 13),
                          trailing: Flex(
                              direction: Axis.vertical,
                              mainAxisSize: MainAxisSize.max,
                              children: [
                                IconButton(
                                  padding: EdgeInsets.all(0),
                                  alignment: Alignment.topCenter,
                                  visualDensity: VisualDensity.compact,
                                  icon: Icon(Icons.close_rounded),
                                  onPressed: () {
                                    showRemovalDialog(
                                        'Activity Removal',
                                        'Would you like to permanently remove this activity from the current session?',
                                        context, () {
                                      SessionActivitiesDao(
                                              Provider.of<AppDatabase>(context,
                                                  listen: false))
                                          .removeAssociation(widget.activity.id,
                                              widget.session.id);
                                    }).then((result) {
                                      setState(() {});
                                    });
                                  },
                                )
                              ])),
                    ],
                  )),
            );
          } else {
            return GenericProgressIndicator();
          }
        });
  }
}
