import 'dart:convert';

import 'package:drift/drift.dart' hide Column;
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:sendtrain/daos/sessions_dao.dart';
import 'package:sendtrain/database/database.dart';
import 'package:sendtrain/widgets/generic/elements/form_text_input.dart';

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

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

  @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('Create Achievement',
                          textAlign: TextAlign.center,
                          style: Theme.of(context).textTheme.titleLarge)),
                  FormTextInput(controller: tec, title: 'Achievement', icon: Icon(Icons.military_tech_rounded)),
                  Row(mainAxisAlignment: MainAxisAlignment.end, children: [
                    Padding(
                        padding: EdgeInsets.only(top: 10),
                        child: FilledButton(
                            child: Text('Submit'),
                            onPressed: () async {
                              session.achievements;
                              List achievements =
                                  json.decode(session.achievements ?? "[]");
                              achievements.add(tec.text);
                              Session updatedSession = session.copyWith(
                                  achievements:
                                      Value<String>(json.encode(achievements)));

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

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

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