mirrored_repositories/Expenses_Tracker_App/lib/screens/add_expense
import 'dart:math';
import 'package:expense_repository/expense_repository.dart';
import 'package:expenses_tracker/utils/constants/tr_text.dart';
import 'package:expenses_tracker/utils/extensions/string_extensions.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:intl/intl.dart';
import 'package:uuid/uuid.dart';
import 'package:expenses_tracker/bloc/create_expense_bloc/create_expense_bloc.dart';
import 'package:expenses_tracker/screens/add_expense/widgets/save_button.dart';
import 'package:expenses_tracker/utils/constants/colors.dart';
import 'package:expenses_tracker/utils/constants/sizes.dart';
import 'package:expenses_tracker/utils/helpers/helpers.dart';

class AddScreen extends StatefulWidget {
  final Function(List<Expense>) refreshHomeScreen;
  const AddScreen({
    super.key,
    required this.refreshHomeScreen,
  });

  @override
  // ignore: library_private_types_in_public_api
  _AddScreenState createState() => _AddScreenState();
}

class _AddScreenState extends State<AddScreen> {
  late Expense expenseModel;
  bool isLoading = false;

  DateTime date = DateTime.now();

  final TextEditingController explainController = TextEditingController();
  final TextEditingController amountController = TextEditingController();
  final TextEditingController dateController = TextEditingController();
  FocusNode explain = FocusNode();
  FocusNode amount = FocusNode();

  String? selectedItem;
  String? selectedImagePath;
  String? selectedHow;
  String? selectedUnit;

  final List<String> _item = [
    'card',
    'dress',
    'education',
    'entertainment',
    'food',
    'health',
    'holiday',
    'transportation',
    'travel',
    'sport',
    'shopping',
    'pet',
    'transfer',
    'investment',
    'other',
  ];
  final List<String> _itemExpense = ['Income', 'Expense'];

  final List<String> _currencyUnit = ["\$", "€", "£", "₺", "XAU"];

  late CreateExpenseBloc _createExpensesBloc;
  @override
  void initState() {
    expenseModel = Expense.empty;
    expenseModel.expenseId = const Uuid().v1();
    amount.addListener(() {
      setState(() {});
    });
    explain.addListener(() {
      setState(() {});
    });
    _createExpensesBloc = CreateExpenseBloc(FirebaseExpenseRepo());
    _createExpensesBloc.add(CreateExpense(Expense.empty));
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) => _createExpensesBloc,
      child: BlocBuilder<CreateExpenseBloc, CreateExpenseState>(
        builder: (context, state) {
          if (state is CreateExpenseLoading) {
            return const Center(child: CircularProgressIndicator());
          }
          if (state is CreateExpenseSuccess) {
            return Scaffold(
              body: SafeArea(
                child: Stack(
                  alignment: Alignment.center,
                  children: [
                    backgroundContainer(context),
                    Positioned(
                      top: 100,
                      child: mainContainer(),
                    ),
                  ],
                ),
              ),
            );
          }
          if (state is CreateExpenseFailure) {
            return const Center(child: Text('Failed to fetch expenses'));
          }
          return Container();
        },
      ),
    );
  }

  Container mainContainer() {
    final dark = EHelperFunctions.isDarkMode(context);
    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(ESizes.paddingXl),
        color: dark ? EColors.darker : EColors.lightContainer,
      ),
      height: MediaQuery.of(context).size.width * 1.6,
      width: MediaQuery.of(context).size.width * 0.85,
      child: Column(
        children: [
          const SizedBox(height: ESizes.containerSize),
          categoryName(),
          const SizedBox(height: ESizes.paddingXl),
          explainExpense(),
          const SizedBox(height: ESizes.paddingXl),
          amountValue(),
          const SizedBox(height: ESizes.paddingXl),
          currencyUnit(),
          const SizedBox(height: ESizes.paddingXl),
          howCome(),
          const SizedBox(height: ESizes.paddingXl),
          dateTime(),
          const SizedBox(height: ESizes.paddingXxl),
          isLoading
              ? const Center(child: CircularProgressIndicator())
              : saveButton(context),
        ],
      ),
    );
  }

  Padding saveButton(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: ESizes.md),
      child: BlocProvider<CreateExpenseBloc>.value(
        value: context.read<CreateExpenseBloc>(),
        child: SaveButton(
          onPressed: () {
            setState(() {
              expenseModel.amount = int.parse(amountController.text);
              expenseModel.explain = explainController.text;
            });
            context.read<CreateExpenseBloc>().add(CreateExpense(expenseModel));
            Navigator.pop(context, expenseModel);
          },
        ),
      ),
    );
  }

  Padding dateTime() {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: ESizes.md),
      child: SizedBox(
        width: MediaQuery.of(context).size.width * 0.95,
        child: TextFormField(
          controller: dateController,
          onTap: () async {
            DateTime? newDate = await showDatePicker(
              context: context,
              initialDate: expenseModel.date,
              firstDate: DateTime(2020),
              lastDate: DateTime(2100),
            );
            if (newDate != null) {
              dateController.text =
                  DateFormat(ETexts.dateFormat).format(newDate);

              expenseModel.date = newDate;
            }
          },
          readOnly: true, // klavye çıkmaz,
          textAlignVertical: TextAlignVertical.center,
          keyboardType: TextInputType.datetime,
          decoration: InputDecoration(
            contentPadding: const EdgeInsets.symmetric(
                horizontal: ESizes.md, vertical: ESizes.md),
            enabledBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(ESizes.iconXs),
              borderSide:
                  const BorderSide(width: 1.5, color: EColors.borderPrimary),
            ),
            prefixIcon: const Icon(Icons.calendar_month_outlined),
            labelText: ETexts.date,
          ),
        ),
      ),
    );
  }

  Padding howCome() {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: ESizes.md),
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: ESizes.md),
        width: MediaQuery.of(context).size.width * 0.88,
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(ESizes.iconXs),
            border: Border.all(width: 1.5, color: EColors.borderPrimary)),
        child: DropdownButton<String>(
          value: selectedHow,
          onChanged: (value) {
            setState(() {
              selectedHow = value!;
              expenseModel.howExpense = value;
            });
          },
          items: _itemExpense
              .map((e) => DropdownMenuItem(
                    value: e,
                    child: Text(e.capitalizeFirstLetter(),
                        style: Theme.of(context).textTheme.titleMedium),
                  ))
              .toList(),
          hint: Text(
            ETexts.how,
            style: Theme.of(context)
                .textTheme
                .titleMedium!
                .apply(color: EColors.darkGrey),
          ),
          isExpanded: true,
          underline: Container(),
        ),
      ),
    );
  }

  Padding currencyUnit() {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: ESizes.md),
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: ESizes.md),
        width: MediaQuery.of(context).size.width * 0.88,
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(ESizes.iconXs),
            border: Border.all(width: 1.5, color: EColors.borderPrimary)),
        child: DropdownButton<String>(
          value: selectedUnit,
          onChanged: (value) {
            setState(() {
              selectedUnit = value!;
              expenseModel.currency = value;
            });
          },
          items: _currencyUnit
              .map((e) => DropdownMenuItem(
                    value: e,
                    child:
                        Text(e, style: Theme.of(context).textTheme.titleMedium),
                  ))
              .toList(),
          hint: Text(
            ETexts.currency,
            style: Theme.of(context)
                .textTheme
                .titleMedium!
                .apply(color: EColors.darkGrey),
          ),
          isExpanded: true,
          underline: Container(),
        ),
      ),
    );
  }

  Padding amountValue() {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: ESizes.md),
      child: TextFormField(
        keyboardType: TextInputType.number,
        controller: amountController,
        focusNode: amount,
        decoration: InputDecoration(
          contentPadding: const EdgeInsets.symmetric(
              horizontal: ESizes.md, vertical: ESizes.md),
          labelText: ETexts.amount,
          labelStyle: Theme.of(context)
              .textTheme
              .titleMedium!
              .apply(color: EColors.darkGrey),
          enabledBorder: OutlineInputBorder(
            borderRadius: BorderRadius.circular(ESizes.iconXs),
            borderSide:
                const BorderSide(width: 1.5, color: EColors.borderPrimary),
          ),
        ),
      ),
    );
  }

  Padding explainExpense() {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: ESizes.md),
      child: TextFormField(
        controller: explainController,
        focusNode: explain,
        decoration: InputDecoration(
            contentPadding: const EdgeInsets.symmetric(
                horizontal: ESizes.md, vertical: ESizes.md),
            labelText: ETexts.explain,
            labelStyle: Theme.of(context)
                .textTheme
                .titleMedium!
                .apply(color: EColors.darkGrey),
            enabledBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(ESizes.iconXs),
                borderSide: const BorderSide(
                    width: 1.5, color: EColors.borderPrimary))),
      ),
    );
  }

  Padding categoryName() {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: ESizes.md),
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: ESizes.md),
        width: MediaQuery.of(context).size.width * 0.88,
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(ESizes.iconXs),
            border: Border.all(width: 1.5, color: EColors.borderPrimary)),
        child: DropdownButton<String>(
          value: selectedItem,
          onChanged: (value) {
            setState(() {
              selectedItem = value!;
              // Seçilen kategoriye göre resim yolunu belirle
              selectedImagePath = 'assets/images/$value.png';
              // Expense modelini güncelle
              expenseModel.categoryName = value;
              expenseModel.categoryImagePath = selectedImagePath.toString();
              expenseModel.categoryId = const Uuid().v1();
            });
          },
          items: _item
              .map((e) => DropdownMenuItem(
                    value: e,
                    child: Row(
                      children: [
                        SizedBox(
                            width: ESizes.paddingXxl,
                            child: Image(
                                image: AssetImage('assets/images/$e.png'))),
                        const SizedBox(width: 10),
                        Text(e.capitalizeFirstLetter(),
                            style: Theme.of(context).textTheme.titleMedium),
                      ],
                    ),
                  ))
              .toList(),
          hint: Text(
            ETexts.category,
            style: Theme.of(context)
                .textTheme
                .titleMedium!
                .apply(color: EColors.darkGrey),
          ),
          isExpanded: true,
          underline: Container(),
        ),
      ),
    );
  }

  Column backgroundContainer(BuildContext context) {
    return Column(
      children: [
        Container(
          width: double.infinity,
          height: MediaQuery.of(context).size.width * 0.55,
          decoration: const BoxDecoration(
            gradient: LinearGradient(colors: [
              EColors.primary,
              EColors.secondary,
              EColors.tertiary,
            ], transform: GradientRotation(pi / 4)),
            borderRadius: BorderRadius.only(
              bottomLeft: Radius.circular(ESizes.containerSize),
              bottomRight: Radius.circular(ESizes.containerSize),
            ),
          ),
          child: Column(
            children: [
              const SizedBox(height: ESizes.paddingXxl),
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: ESizes.md),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    GestureDetector(
                      onTap: () {
                        Navigator.pop(context);
                      },
                      child: const Icon(
                        Icons.arrow_back_ios_new_rounded,
                        color: EColors.grey,
                      ),
                    ),
                    Text(
                      ETexts.addExpenses,
                      style: Theme.of(context)
                          .textTheme
                          .headlineSmall!
                          .apply(color: EColors.white),
                    ),
                    const SizedBox(height: ESizes.md),
                  ],
                ),
              )
            ],
          ),
        ),
      ],
    );
  }
}
