import 'package:drift/drift.dart' show Value;
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:get_it/get_it.dart';
import 'package:okane/database/sqlite.dart';
import 'package:okane/i18n/strings.g.dart';
import 'package:okane/ui/state/core.dart';
import 'package:searchfield/searchfield.dart';

class AddLoanPopup extends StatefulWidget {
  final VoidCallback onDone;

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

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

class AddBudgetState extends State<AddLoanPopup> {
  final TextEditingController _beneficiaryTextController =
      TextEditingController();
  SearchFieldListItem<Beneficiary>? _selectedBeneficiary;

  String getBeneficiaryName(Beneficiary item) {
    return switch (item.type) {
      BeneficiaryType.account => t.common.beneficiary.nameWithAccount(
        name: item.name,
      ),
      BeneficiaryType.other => item.name,
    };
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Padding(
          padding: const EdgeInsets.symmetric(vertical: 8),
          child: BlocBuilder<CoreCubit, CoreState>(
            builder:
                (context, state) => SearchField<Beneficiary>(
                  suggestions:
                      state.beneficiaries
                          .where((el) {
                            final bloc = GetIt.I.get<CoreCubit>();
                            if (el.type == BeneficiaryType.account) {
                              return el.accountId ==
                                  bloc.activeAccount?.id.toInt();
                            }
                            return true;
                          })
                          .map((el) {
                            return SearchFieldListItem(
                              getBeneficiaryName(el),
                              item: el,
                            );
                          })
                          .toList(),
                  hint: "Beneficiary",
                  controller: _beneficiaryTextController,
                  selectedValue: _selectedBeneficiary,
                  onSuggestionTap: (beneficiary) {
                    setState(() => _selectedBeneficiary = beneficiary);
                  },
                ),
          ),
        ),

        Row(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            OutlinedButton(
              onPressed: () async {
                final beneficiaryName = _beneficiaryTextController.text;
                if (_selectedBeneficiary == null && beneficiaryName.isEmpty) {
                  return;
                }

                final db = GetIt.I.get<OkaneDatabase>();
                Beneficiary? beneficiary = _selectedBeneficiary?.item;
                if (beneficiary == null ||
                    getBeneficiaryName(beneficiary) != beneficiaryName) {
                  // Add a new beneficiary, if none was selected
                  final result = await showDialog<bool>(
                    context: context,
                    builder:
                        (context) => AlertDialog(
                          title: Text(
                            t.common.beneficiary.addBeneficiary.title,
                          ),
                          content: Text(
                            t.common.beneficiary.addBeneficiary.body(
                              name: beneficiaryName,
                            ),
                          ),
                          actions: [
                            TextButton(
                              style: TextButton.styleFrom(
                                textStyle:
                                    Theme.of(context).textTheme.labelLarge,
                              ),
                              child: Text(t.modals.add),
                              onPressed: () => Navigator.of(context).pop(true),
                            ),
                            TextButton(
                              style: TextButton.styleFrom(
                                textStyle:
                                    Theme.of(context).textTheme.labelLarge,
                              ),
                              child: Text(t.modals.cancel),
                              onPressed: () => Navigator.of(context).pop(false),
                            ),
                          ],
                        ),
                  );
                  if (result == null || !result) {
                    return;
                  }

                  beneficiary = await db.beneficiariesDao.upsertBeneficiary(
                    BeneficiariesCompanion(
                      name: Value(beneficiaryName),
                      type: Value(BeneficiaryType.other),
                    ),
                  );
                }

                await db.loansDao.upsertLoan(
                  LoansCompanion(beneficiaryId: Value(beneficiary.id)),
                );
                widget.onDone();
              },
              child: Text(t.modals.add),
            ),
          ],
        ),
      ],
    );
  }
}