import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:helpers/helpers/misc_build/build_media.dart';
import 'package:intl/intl.dart';
import 'package:rluv/features/budget/screens/transactions_listview.dart';
import 'package:rluv/features/budget/widgets/add_transaction_dialog.dart';
import 'package:rluv/global/api.dart';
import 'package:rluv/global/utils.dart';
import 'package:rluv/models/transaction_model.dart';

import '../../../global/store.dart';
import '../../../global/styles.dart';
import '../../../global/widgets/budget_color_circle.dart';
import '../../../models/budget_category_model.dart';

class TransactionListItem extends ConsumerStatefulWidget {
  const TransactionListItem({super.key, required this.index});

  final int index;

  @override
  ConsumerState<TransactionListItem> createState() =>
      _TransactionListItemState();
}

class _TransactionListItemState extends ConsumerState<TransactionListItem> {
  bool showDetails = false;
  double cardHeight = 70.0;

  BudgetCategory? budgetCategory;
  Transaction? transaction;

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

  @override
  Widget build(BuildContext context) {
    transaction =
        // ignore: sdk_version_since
        ref.watch(transactionHistoryListProvider).elementAtOrNull(widget.index);
    if (transaction == null) return Container();
    final budgetCategories = ref.read(budgetCategoriesProvider);
    if (transaction!.type == TransactionType.expense) {
      budgetCategory = budgetCategories.singleWhere(
        (category) => category.id == transaction!.budgetCategoryId,
      );
    } else {
      budgetCategory = null;
    }
    return GestureDetector(
      onTap: () => toggleDetails(),
      child: Padding(
        padding: const EdgeInsets.only(top: 8.0, left: 8.0, bottom: 8.0),
        child: ClipRRect(
          borderRadius: const BorderRadius.only(
              topLeft: Radius.circular(10.0),
              bottomLeft: Radius.circular(10.0)),
          child: AnimatedContainer(
            curve: Curves.easeOut,
            duration: const Duration(milliseconds: 200),
            height: cardHeight,
            decoration: const BoxDecoration(
              borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(10.0),
                  bottomLeft: Radius.circular(10.0)),
              color: Styles.washedStone,
            ),
            child: Row(
              children: [
                AnimatedContainer(
                    curve: Curves.easeOut,
                    duration: const Duration(milliseconds: 200),
                    height: cardHeight,
                    width: 6,
                    color: transaction!.type == TransactionType.income
                        ? Styles.incomeBlue
                        : Styles.expensesOrange),
                SizedBox(
                  width: BuildMedia(context).width * 0.65,
                  child: Padding(
                    padding: const EdgeInsets.only(left: 8.0),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(DateFormat('EEE MMM d, h:mm a')
                            .format(transaction!.date)),
                        Row(
                          children: [
                            const SizedBox(
                              width: 6,
                            ),
                            if (budgetCategory != null) ...[
                              BudgetColorCircle(
                                color: budgetCategory!.color,
                              ),
                              const SizedBox(
                                width: 8,
                              ),
                            ],
                            Text(
                              transaction!.type == TransactionType.income
                                  ? 'Income'
                                  : budgetCategory!.name,
                              style: const TextStyle(fontSize: 20),
                            ),
                          ],
                        ),
                        if (showDetails)
                          Text(
                            transaction!.memo ?? '',
                            style: const TextStyle(fontSize: 16),
                          )
                      ],
                    ),
                  ),
                ),
                const Spacer(),
                Column(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    Text(
                      transaction!.amount.currency(),
                      style: TextStyle(
                          fontSize: 24,
                          color: transaction!.type == TransactionType.income
                              ? Styles.incomeGreen
                              : Styles.expensesRed),
                    ),
                    if (showDetails) ...[
                      IconButton(
                        icon: const Icon(
                          Icons.edit_rounded,
                        ),
                        onPressed: () {
                          showDialog(
                            context: context,
                            builder: (context) => Dialog(
                              backgroundColor: Styles.dialogColor,
                              shape: Styles.dialogShape,
                              child:
                                  TransactionDialog(transaction: transaction),
                            ),
                          );
                        },
                      ),
                      IconButton(
                        icon: const Icon(
                          Icons.delete,
                          color: Styles.expensesRed,
                        ),
                        onPressed: () => deleteTransaction(),
                      ),
                    ],
                  ],
                ),
                const SizedBox(
                  width: 14,
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  void toggleDetails() {
    if (showDetails) {
      setState(() {
        showDetails = false;
        cardHeight = 70;
      });
    } else {
      setState(() {
        showDetails = true;
        cardHeight = 120;
      });
    }
  }

  Future deleteTransaction() async {
    final res = await ref
        .read(apiProvider.notifier)
        .delete(path: 'transaction', data: {'id': transaction!.id});

    final success = res != null ? res['success'] as bool : false;
    if (success) {
      ref
          .read(dashboardProvider.notifier)
          .removeWithId('transactions', transaction!.id!);
      showSnack(ref: ref, text: 'Transaction removed', type: SnackType.success);
    } else {
      showSnack(
          ref: ref,
          text: 'Could not delete transaction',
          type: SnackType.error);
    }
  }
}
