import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:intl/intl.dart';
import 'package:krezus/domains/budget/budget_bloc.dart';
import 'package:krezus/domains/category/category_bloc.dart';
import 'package:krezus/pages/budgets/widgets/budget_line.dart';
import 'package:krezus/pages/common/titled_container.dart';
import 'package:krezus/repositories/metadata/models/budget.dart';

class BudgetMaker extends StatelessWidget {
  const BudgetMaker({super.key});

  List<Widget> _computeBudgetLines(BuildContext context, List<Budget> budgets, double initialBudget, double remainingBudget) {
    List<Widget> list = [];

    list.add(
      Container(
        margin: const EdgeInsets.only(top: 5, bottom: 5),
        padding: const EdgeInsets.only(bottom: 10),
        child: Flex(
          direction: Axis.horizontal,
          children: [Expanded(
          child: 
            TextFormField(
              keyboardType: const TextInputType.numberWithOptions(decimal: false),
              decoration: InputDecoration(
                icon: const Icon(Icons.euro),
                hintText: '\$\$\$',
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(5),
                ),
              ),
              initialValue: initialBudget.toString(),
              onChanged: (value) => context.read<BudgetBloc>().add(BudgetSetInitial(double.parse(value)))
            )
          
        )]
      ))
    );

    list.addAll(budgets.map((budget) => BudgetLine(budget: budget)).toList());

    list.add(
      Container(
        margin: const EdgeInsets.only(top: 25, bottom: 5),
        decoration: BoxDecoration(
          border: Border(
            bottom: BorderSide(
              width: 2,
              color: Theme.of(context).colorScheme.onPrimaryContainer
            )
          )
        ),
      )
    );

    list.add(
      Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          Text(
            '${NumberFormat('#####00 €', 'fr_FR').format(remainingBudget)} remaining  ',
            style: const TextStyle(
              fontFamily: 'NovaMono',
              fontWeight: FontWeight.bold,
              fontSize: 15,
            )
          )
        ],
      )
    );
    return list;
  }

  @override
  Widget build(BuildContext context) {
    final categoryState = context.watch<CategoryBloc>().state;
    return BlocBuilder<BudgetBloc, BudgetState>(
      builder: (context, state) => TitledContainer(
        title: 'Prepare',
        action: IconButton(
          onPressed: () => context.read<BudgetBloc>().add(BudgetAdd(categoryState.categories.first.label)),
          icon: const Icon(Icons.add),
        ),
        child: Column(
          children: _computeBudgetLines(context, state.budgets, state.initialBudget, state.remainingBudget),
        ),
      )
    );
  }
}