import 'package:drift/drift.dart' hide Column;
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:sendtrain/daos/session_activities_dao.dart';
import 'package:sendtrain/database/database.dart';
import 'package:sendtrain/services/search/activity_finder_service.dart';
import 'package:sendtrain/widgets/generic/elements/form_search_input.dart';

class SessionActivitiesEditor extends StatelessWidget {
  SessionActivitiesEditor({super.key, required this.session, this.callback});

  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final TextEditingController tec = TextEditingController();
  final Session session;
  final Function? callback;
  late final Activity selectedActivity;

  @override
  Widget build(
    BuildContext context,
  ) {
    return Padding(
        padding: EdgeInsets.fromLTRB(15, 0, 15, 15),
        child: Form(
            key: _formKey,
            child: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  Padding(
                      padding: EdgeInsets.only(top: 10, bottom: 10),
                      child: Text('Add Activity',
                          textAlign: TextAlign.center,
                          style: Theme.of(context).textTheme.titleLarge)),
                  FormSearchInput(
                      title: 'Find an Activity',
                      controller: tec,
                      service: ActivityFinderService(context),
                      resultHandler: (Activity content,
                          ActivityFinderService service) async {
                        tec.text = content.title;
                        selectedActivity = content;
                      }),
                  Row(mainAxisAlignment: MainAxisAlignment.end, children: [
                    Padding(
                        padding: EdgeInsets.only(top: 10),
                        child: FilledButton(
                            child: Text('Submit'),
                            onPressed: () async {
                              final SessionActivitiesDao dao =
                                  SessionActivitiesDao(
                                      Provider.of<AppDatabase>(context, listen: false));

                              await dao.createOrUpdate(SessionActivitiesCompanion(
                                sessionId: Value(session.id),
                                activityId: Value(selectedActivity.id),
                                position: Value(0),
                              ));

                              Navigator.pop(_formKey.currentContext!, 'Submit');

                              if (callback != null) {
                                await callback!();
                              }
                            }))
                  ])
                ])));
  }
}
