import 'dart:convert';

import 'package:flutter/material.dart' hide Action;
import 'package:flutter_expandable_fab/flutter_expandable_fab.dart';
import 'package:provider/provider.dart';
import 'package:sendtrain/daos/actions_dao.dart';
import 'package:sendtrain/database/database.dart';
import 'package:sendtrain/extensions/string_extensions.dart';
import 'package:sendtrain/helpers/widget_helpers.dart';
import 'package:sendtrain/providers/action_timer.dart';
import 'package:sendtrain/widgets/activities/activity_action_editor.dart';
import 'package:sendtrain/widgets/activities/activity_action_view.dart';
import 'package:sendtrain/widgets/activities/activity_view_categories.dart';
import 'package:sendtrain/widgets/activities/activity_view_media.dart';
import 'package:sendtrain/widgets/builders/dialogs.dart';

class ActivityView extends StatefulWidget {
  const ActivityView(
      {super.key, required this.session, required this.activity});
  final Session session;
  final Activity activity;

  @override
  State<ActivityView> createState() => _ActivityViewState();
}

class _ActivityViewState extends State<ActivityView> {
  final _fabKey = GlobalKey<ExpandableFabState>();

  void resetState() async {
    final state = _fabKey.currentState;
    if (state != null && state.isOpen) {
      state.toggle();
    }

    setState(() {});
  }

  List<ActivityMuscle> activityMuscle(Activity activity) {
    List<ActivityMuscle> muscles = [];

    if (activity.primaryMuscles != null) {
      muscles.add(activity.primaryMuscles!);
    }

    if (activity.secondaryMuscles != null) {
      muscles.add(activity.secondaryMuscles!);
    }

    return muscles;
  }

  @override
  Widget build(BuildContext context) {
    final Activity activity = widget.activity;
    final Session session = widget.session;

    return FutureBuilder<List>(
        future: ActionsDao(Provider.of<AppDatabase>(context))
            .fromActivity(activity, session),
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            List<Action> actions = snapshot.data! as List<Action>;

            return PopScope(
                canPop: false,
                onPopInvokedWithResult: (didPop, result) async {
                  if (didPop) {
                    return;
                  }
                  final bool shouldPop = await showBackDialog(context) ?? false;
                  if (context.mounted && shouldPop) {
                    Navigator.pop(context);
                  }
                },
                child: Scaffold(
                    floatingActionButtonLocation: ExpandableFab.location,
                    floatingActionButton: ExpandableFab(
                        key: _fabKey,
                        distance: 70,
                        type: ExpandableFabType.up,
                        overlayStyle: ExpandableFabOverlayStyle(
                          color: Colors.black.withOpacity(0.5),
                          blur: 10,
                        ),
                        onOpen: () {
                          // pause the activity on open
                          ActionTimer at =
                              Provider.of<ActionTimer>(context, listen: false);
                          if (at.started) at.pause();
                        },
                        children: [
                          // FloatingActionButton.extended(
                          //   icon: const Icon(Icons.upload_outlined),
                          //   label: Text('Upload Media'),
                          //   onPressed: () {},
                          // ),
                          FloatingActionButton.extended(
                            icon: const Icon(Icons.done_all_outlined),
                            label: Text('Edit Action'),
                            onPressed: () {
                              showEditorSheet(
                                  context,
                                  ActivityActionEditor(
                                      session: session,
                                      activity: activity,
                                      action: actions.first,
                                      callback: resetState));
                            },
                          ),
                          FloatingActionButton.extended(
                            icon: const Icon(Icons.note_add_outlined),
                            label: Text('Add Note'),
                            onPressed: () {},
                          ),
                          FloatingActionButton.extended(
                            icon: const Icon(Icons.history_outlined),
                            label: Text('Restart'),
                            onPressed: () {},
                          ),
                          FloatingActionButton.extended(
                            icon: const Icon(Icons.done_all_outlined),
                            label: Text('Done'),
                            onPressed: () {},
                          ),
                        ]),
                    body: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          AppBar(
                            titleSpacing: 0,
                            centerTitle: true,
                            title: const Text('Activity',
                                style: TextStyle(fontSize: 15)),
                          ),
                          Padding(
                              padding: const EdgeInsets.only(
                                  left: 15, right: 20, top: 15, bottom: 10),
                              child: Text(
                                  maxLines: 1,
                                  style: const TextStyle(
                                      fontSize: 25,
                                      fontWeight: FontWeight.bold),
                                  activity.title.toTitleCase())),
                          SizedBox(
                              height: 40,
                              child: ListView(
                                  scrollDirection: Axis.horizontal,
                                  padding:
                                      const EdgeInsets.fromLTRB(10, 0, 10, 0),
                                  shrinkWrap: true,
                                  children: [
                                    ActivityViewCategories<List<ActivityLevel>>(
                                        icon: Icon(Icons.stairs_rounded),
                                        text: "Activity Level",
                                        object: activity.level != null
                                            ? [activity.level!]
                                            : []),
                                    // ActivityViewCategories<List<ActivityMechanic>>(
                                    //     icon: Icon(Icons.),
                                    //     text: 'Activity Mechanic',
                                    //     object: activity.mechanic != null
                                    //         ? [activity.mechanic!]
                                    //         : []),
                                    ActivityViewCategories<
                                            List<ActivityEquipment>>(
                                        icon:
                                            Icon(Icons.fitness_center_rounded),
                                        text: 'Equipment Used',
                                        object: activity.equipment != null
                                            ? [activity.equipment!]
                                            : []),
                                    ActivityViewCategories<List<ActivityType>>(
                                        icon: Icon(Icons.type_specimen_rounded),
                                        text: 'Activity Type',
                                        object: activity.type != null
                                            ? [activity.type!]
                                            : []),
                                    ActivityViewCategories<
                                            List<ActivityMuscle>>(
                                        icon: Icon(Icons.person),
                                        text: 'Muscles used',
                                        object: activityMuscle(activity))
                                  ])),
                          Padding(
                              padding: const EdgeInsets.only(
                                  top: 10, bottom: 0, left: 15, right: 15),
                              child: Text(
                                  maxLines: 4,
                                  overflow: TextOverflow.ellipsis,
                                  // softWrap: true,
                                  textAlign: TextAlign.left,
                                  style: const TextStyle(fontSize: 15),
                                  jsonToDescription([
                                    json.decode(activity.description ?? "")[0]
                                  ]))),
                          Padding(
                              padding: EdgeInsets.only(right: 15),
                              child: Align(
                                  alignment: Alignment.topRight,
                                  child: TextButton(
                                    style: ButtonStyle(
                                        textStyle:
                                            WidgetStateProperty.all<TextStyle>(
                                                TextStyle(
                                                    fontWeight:
                                                        FontWeight.normal)),
                                        shape: WidgetStateProperty.all<
                                                RoundedRectangleBorder>(
                                            RoundedRectangleBorder(
                                          borderRadius:
                                              BorderRadius.circular(10.0),
                                        ))),
                                    onPressed: () {
                                      showGenericSheet(
                                          context,
                                          Padding(
                                              padding: EdgeInsets.all(15),
                                              child: Text(
                                                  style:
                                                      TextStyle(fontSize: 18),
                                                  jsonToDescription(json.decode(
                                                      activity.description ??
                                                          "")))));
                                    },
                                    child: Text(
                                      "read more",
                                      textAlign: TextAlign.right,
                                      style: TextStyle(fontSize: 12),
                                    ),
                                  ))),
                          const Padding(
                              padding: EdgeInsets.fromLTRB(15, 10, 0, 10),
                              child: Text(
                                  style: TextStyle(
                                      fontSize: 20,
                                      fontWeight: FontWeight.bold),
                                  'Media:')),
                          ActivityViewMedia(activity: activity),
                          Padding(
                              padding: const EdgeInsets.fromLTRB(15, 20, 5, 0),
                              child: Row(children: [
                                Expanded(
                                    child: const Text(
                                        textAlign: TextAlign.left,
                                        style: TextStyle(
                                            fontSize: 20,
                                            fontWeight: FontWeight.bold),
                                        'Actions')),
                                IconButton(
                                  onPressed: () {
                                    showGenericSheet(
                                        context,
                                        Column(children: [
                                          ActivityActionView(
                                              session: session,
                                              activity: activity,
                                              actions: actions,
                                              callback: resetState,
                                              resetOnLoad: false)
                                        ]),
                                        Theme.of(context).colorScheme.surface);
                                  },
                                  icon: Icon(Icons.expand),
                                  alignment: Alignment.bottomCenter,
                                )
                              ])),
                          ActivityActionView(
                              session: session,
                              activity: activity,
                              actions: actions,
                              callback: resetState)
                        ])));
            // ] +
            // action(actions, context)));
          } else {
            return Container(
                alignment: Alignment.center,
                child: SizedBox(
                  height: 50.0,
                  width: 50.0,
                  child: CircularProgressIndicator(),
                ));
          }
        });
  }
}
