import 'package:flutter/material.dart';
import 'package:okane/database/collections/budget.dart';
import 'package:okane/database/database.dart';

class EditBudgetPopup extends StatefulWidget {
  final Budget budget;

  final VoidCallback onDone;

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

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

class EditBudgetState extends State<EditBudgetPopup> {
  final _budgetNameEditController = TextEditingController();

  late bool _includeOtherSpendings;

  @override
  void initState() {
    super.initState();

    _budgetNameEditController.text = widget.budget.name;
    _includeOtherSpendings = widget.budget.includeOtherSpendings;
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        TextField(
          decoration: InputDecoration(hintText: "Name"),
          controller: _budgetNameEditController,
        ),
        Row(
          children: [
            Text("Include other spendings"),
            Switch(
              value: _includeOtherSpendings,
              onChanged: (value) {
                setState(() => _includeOtherSpendings = value);
              },
            ),
          ],
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            OutlinedButton(
              onPressed: () async {
                if (_budgetNameEditController.text.isEmpty) {
                  return;
                }
                if (_budgetNameEditController.text == widget.budget.name &&
                    _includeOtherSpendings ==
                        widget.budget.includeOtherSpendings) {
                  widget.onDone();
                  return;
                }

                widget.budget
                  ..name = _budgetNameEditController.text
                  ..includeOtherSpendings = _includeOtherSpendings;
                await upsertBudget(widget.budget);
                widget.onDone();
              },
              child: Text("Save"),
            ),
          ],
        ),
      ],
    );
  }
}