import 'package:flutter/material.dart';
import 'package:get_it/get_it.dart';
import 'package:okane/database/collections/budget.dart';
import 'package:okane/database/database.dart';
import 'package:okane/ui/state/core.dart';

class AddBudgetPopup extends StatefulWidget {
  final VoidCallback onDone;

  const AddBudgetPopup({super.key, required this.onDone});

  @override
  AddBudgetState createState() => AddBudgetState();
}

class AddBudgetState extends State<AddBudgetPopup> {
  final _budgetNameEditController = TextEditingController();
  final _budgetIncomeEditController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        TextField(
          decoration: InputDecoration(hintText: "Budget name"),
          controller: _budgetNameEditController,
        ),

        TextField(
          decoration: InputDecoration(hintText: "Income"),
          controller: _budgetIncomeEditController,
          keyboardType: TextInputType.numberWithOptions(
            signed: false,
            decimal: true,
          ),
        ),

        Row(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            OutlinedButton(
              onPressed: () async {
                if (_budgetNameEditController.text.isEmpty ||
                    _budgetIncomeEditController.text.isEmpty) {
                  return;
                }

                final bloc = GetIt.I.get<CoreCubit>();
                final budget =
                    Budget()
                      ..name = _budgetNameEditController.text
                      ..period = BudgetPeriod.month
                      ..includeOtherSpendings = false
                      ..income = double.parse(_budgetIncomeEditController.text)
                      ..account.value = bloc.activeAccount!;
                await upsertBudget(budget);
                widget.onDone();
              },
              child: Text("Add"),
            ),
          ],
        ),
      ],
    );
  }
}