import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:intl/intl.dart';
import 'package:krezus/domains/account/account_bloc.dart';
import 'package:krezus/domains/category/category_bloc.dart';
import 'package:krezus/domains/transaction/transaction_bloc.dart';

class TransactionForm extends StatelessWidget {

  const TransactionForm({super.key});

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        _TransactionDateInput(),
        const SizedBox(height: 10,),
        _TransactionCategoryInput(),
        const SizedBox(height: 10,),
        _TransactionDescriptionInput(),
        const SizedBox(height: 10,),
        _TransactionAccountInput(),
        const SizedBox(height: 10,),
        _TransactionValueInput()
      ],
    );
  }
}


class _TransactionDateInput extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return BlocBuilder<TransactionBloc, TransactionState>(
      buildWhen: (previous, current) => previous.transactionDate != current.transactionDate,
      builder: (context, state) => SizedBox(
        width: 500,
        child: TextFormField(
          initialValue: DateFormat('dd-MM-yyyy', 'fr_FR').format(state.transactionDate.value ?? DateTime.now()),
          keyboardType: TextInputType.datetime,
          onTap: () {
            FocusScope.of(context).requestFocus(FocusNode());
            showDatePicker(
              context: context,
              firstDate: DateTime.fromMicrosecondsSinceEpoch(0),
              lastDate: DateTime.now()
            ).then((value) {
              if (value != null) {
                context.read<TransactionBloc>().add(TransactionDateChange(value));
              }
            });
          },
          decoration: InputDecoration(
            icon: const Icon(Icons.calendar_month),
            hintText: 'Date',
            errorText: state.transactionDate.isNotValid ? state.transactionDate.error?.message : null,
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(5),
            ),
          ),
        )
      )
    );
  }
}

class _TransactionCategoryInput extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final categoryState = context.watch<CategoryBloc>().state;
    return BlocBuilder<TransactionBloc, TransactionState>(
      buildWhen: (previous, current) => previous.transactionCategory != current.transactionCategory,
      builder: (context, state) => SizedBox(
        width: 500,
        child: DropdownButtonFormField<String>(
          value: state.transactionCategory.value.toString() == '' ?  null : state.transactionCategory.value.toString(),
          onChanged: (value) => context.read<TransactionBloc>().add(TransactionCategoryChange(value!)),
          items: categoryState.categories.map((e) => DropdownMenuItem(value: e.label, child: Text(e.label))).toList(),
          decoration: InputDecoration(
            icon: const Icon(Icons.category),
            hintText: 'Category',
            errorText: state.transactionCategory.isNotValid ? state.transactionCategory.error?.message : null,
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(5),
            ),
          ),
        ),
      ),
    );
  }
}

class _TransactionDescriptionInput extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return BlocBuilder<TransactionBloc, TransactionState>(
      buildWhen: (previous, current) => previous.transactionDescription != current.transactionDescription,
      builder: (context, state) => SizedBox(
        width: 500,
        child: TextFormField(
          decoration: InputDecoration(
            icon: const Icon(Icons.description),
            hintText: 'Description',
            errorText: state.transactionDescription.isNotValid ? state.transactionDescription.error?.message : null,
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(5),
            ),
          ),
          initialValue: state.transactionDescription.value,
          onChanged: (value) => context.read<TransactionBloc>().add(TransactionDescriptionChange(value))
        )
      ),
    );
  }
}

class _TransactionAccountInput extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final accountState = context.watch<AccountBloc>().state;
    return BlocBuilder<TransactionBloc, TransactionState>(
      buildWhen: (previous, current) => previous.transactionAccount != current.transactionAccount,
      builder: (context, state) => SizedBox(
        width: 500,
        child: DropdownButtonFormField<String>(
          value: state.transactionAccount.value.toString() == '' ?  null : state.transactionAccount.value.toString(),
          onChanged: (value) => context.read<TransactionBloc>().add(TransactionAccountChange(value!)),
          items: accountState.accounts.map((e) => DropdownMenuItem(value: e.label, child: Text(e.label))).toList(),
          decoration: InputDecoration(
            icon: const Icon(Icons.account_box),
            hintText: 'Account',
            errorText: state.transactionAccount.isNotValid ? state.transactionAccount.error?.message : null,
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(5),
            ),
          ),
        ),
      ),
    );
  }
}

class _TransactionValueInput extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return BlocBuilder<TransactionBloc, TransactionState>(
      buildWhen: (previous, current) => previous.transactionValue != current.transactionValue,
      builder: (context, state) => SizedBox(
        width: 500,
        child: TextFormField(
          keyboardType: TextInputType.number,
          decoration: InputDecoration(
            icon: const Icon(Icons.euro),
            hintText: '\$\$\$',
            errorText: state.transactionValue.isNotValid ? state.transactionValue.error?.message : null,
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(5),
            ),
          ),
          initialValue: state.transactionValue.value.toString(),
          onChanged: (value) => context.read<TransactionBloc>().add(TransactionValueChange(value))
        )
      ),
    );
  }
}