import 'package:flutter/material.dart';
import 'package:flutter_expandable_fab/flutter_expandable_fab.dart';
import 'package:intl/intl.dart';
import 'package:intl/date_symbol_data_local.dart';
import 'package:provider/provider.dart';

import 'package:sendtrain/daos/sessions_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/widgets/achievements/achievement_editor.dart';
import 'package:sendtrain/widgets/generic/elements/generic_progress_indicator.dart';
import 'package:sendtrain/widgets/sessions/session_activities_editor.dart';
import 'package:sendtrain/widgets/sessions/session_editor.dart';
import 'package:sendtrain/widgets/sessions/session_view_achievements.dart';
import 'package:sendtrain/widgets/sessions/session_view_activities.dart';
import 'package:sendtrain/widgets/sessions/session_view_media.dart';

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

  final Session session;

  @override
  State<SessionView> createState() => _SessionViewState();
}

class _SessionViewState extends State<SessionView> {
  final _fabKey = GlobalKey<ExpandableFabState>();
  late Session session;
  late DateFormat dateFormat;

  String title() {
    String title = session.title.toTitleCase();

    if (session.address != null) {
      title = "$title @ ${session.address}";
    }

    return title;
  }

  void resetState() async {
    Session updatedSession =
        await SessionsDao(Provider.of<AppDatabase>(context, listen: false))
            .find(session.id);

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

    setState(() {
      session = updatedSession;
    });
  }

  @override
  initState() {
    super.initState();
    initializeDateFormatting('en');
    dateFormat = DateFormat('yyyy-MM-dd');
    session = widget.session;
  }

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<Session>(
        initialData: session,
        stream: SessionsDao(Provider.of<AppDatabase>(context))
            .watchSession(session.id),
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            return Scaffold(
                floatingActionButtonLocation: ExpandableFab.location,
                floatingActionButton: ExpandableFab(
                    key: _fabKey,
                    distance: 70,
                    type: ExpandableFabType.up,
                    overlayStyle: ExpandableFabOverlayStyle(
                      color: Colors.black.withOpacity(0.5),
                      blur: 10,
                    ),
                    children: [
                      FloatingActionButton.extended(
                        icon: const Icon(Icons.military_tech_rounded),
                        label: Text('Add Achievement'),
                        onPressed: () {
                          showEditorSheet(
                              context,
                              AchievementEditor(
                                  session: session, callback: resetState));
                        },
                      ),
                      FloatingActionButton.extended(
                        icon: const Icon(Icons.sports_gymnastics_rounded),
                        label: Text('Add Activity'),
                        onPressed: () {
                          showEditorSheet(
                              context,
                              SessionActivitiesEditor(
                                  session: session, callback: resetState));
                        },
                      ),
                      FloatingActionButton.extended(
                        icon: const Icon(Icons.edit_outlined),
                        label: Text('Edit Session'),
                        onPressed: () {
                          showEditorSheet(
                              context,
                              SessionEditor(
                                  session: session, callback: resetState));
                        },
                      ),
                      FloatingActionButton.extended(
                        icon: const Icon(Icons.history_outlined),
                        label: Text('Restart Session'),
                        onPressed: () {
                          Session newSession =
                              session.copyWith(status: SessionStatus.pending);

                          SessionsDao(Provider.of<AppDatabase>(context,
                                  listen: false))
                              .replace(newSession);

                          final state = _fabKey.currentState;
                          if (state != null) {
                            state.toggle();
                          }
                        },
                      ),
                      FloatingActionButton.extended(
                        icon: const Icon(Icons.done_all_outlined),
                        label: Text('Finish Session'),
                        onPressed: () {
                          Session newSession =
                              session.copyWith(status: SessionStatus.completed);

                          SessionsDao(Provider.of<AppDatabase>(context,
                                  listen: false))
                              .replace(newSession);

                          final state = _fabKey.currentState;
                          if (state != null) {
                            state.toggle();
                          }
                        },
                      ),
                    ]),
                body: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    AppBar(
                      centerTitle: true,
                      title: Text(
                          'Session @ ${dateFormat.format(session.date as DateTime)}',
                          style: const 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),
                            title())),
                    SessionViewAchievements(
                        session: session, callback: resetState),
                    Padding(
                        padding: const EdgeInsets.only(left: 15, right: 15),
                        child: Text(
                            style: const TextStyle(fontSize: 15),
                            session.content)),
                    const Padding(
                        padding: EdgeInsets.fromLTRB(15, 30, 0, 10),
                        child: Text(
                            style: TextStyle(
                                fontSize: 20, fontWeight: FontWeight.bold),
                            'Media:')),
                    SessionViewMedia(session: session),
                    const Padding(
                        padding: EdgeInsets.fromLTRB(15, 30, 0, 10),
                        child: Text(
                            style: TextStyle(
                                fontSize: 20, fontWeight: FontWeight.bold),
                            'Activites:')),
                    SessionViewActivities(session: session),
                  ],
                ));
          } else {
            return GenericProgressIndicator();
          }
        });
  }
}
