import 'dart:math';

import 'package:flutter/material.dart';
import 'package:helpers/helpers/print.dart';
import 'package:rluv/features/budget/widgets/add_budget_category_dialog.dart';
import 'package:rluv/global/utils.dart';
import 'package:rluv/models/budget_category_model.dart';

import '../../../global/styles.dart';

class BudgetCategoryBar extends StatefulWidget {
  const BudgetCategoryBar(
      {super.key,
      required this.budgetCategory,
      required this.currentAmount,
      required this.index,
      this.height = 32,
      this.innerPadding = 2.5});

  final int index;
  final double currentAmount;
  final BudgetCategory budgetCategory;
  final double height;
  final double innerPadding;
  @override
  State<BudgetCategoryBar> createState() => _BudgetCategoryBarState();
}

class _BudgetCategoryBarState extends State<BudgetCategoryBar> {
  double percentSpent = 0.0;
  double setTo = 0.0;

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

  @override
  Widget build(BuildContext context) {
    Future.delayed(Duration(milliseconds: min(1600, 200 * widget.index)), () {
      final valToSetTo = widget.currentAmount / widget.budgetCategory.amount;
      if (valToSetTo != setTo) {
        setTo = valToSetTo;
        setState(() => percentSpent = valToSetTo);
      }
    });
    final innerHeight = widget.height - widget.innerPadding * 2;
    final isBright =
        getBrightness(widget.budgetCategory.color) == Brightness.light;
    final textStyle = TextStyle(
        fontSize: 14,
        fontWeight: FontWeight.bold,
        color: widget.currentAmount > widget.budgetCategory.amount
            ? Styles.expensesRed
            : isBright
                ? Colors.black87
                : Colors.white);
    return InkWell(
      onLongPress: () async {
        showDialog(
            context: context,
            builder: (context) => Dialog(
                shape: Styles.dialogShape,
                backgroundColor: Styles.dialogColor,
                child: BudgetCategoryDialog(category: widget.budgetCategory)));
      },
      child: Padding(
        padding: const EdgeInsets.symmetric(vertical: 4.0),
        child: Row(
          children: [
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: SizedBox(
                width: 90,
                child: FittedBox(
                  fit: BoxFit.scaleDown,
                  alignment: Alignment.centerLeft,
                  child: Text(
                    formatBudgetName(widget.budgetCategory.name),
                    style: const TextStyle(fontSize: 18.0),
                  ),
                ),
              ),
            ),
            Expanded(
                child: Padding(
              padding: const EdgeInsets.only(right: 18.0),
              child: Stack(
                children: [
                  Container(
                    height: widget.height,
                    decoration: BoxDecoration(
                      color: Colors.black,
                      borderRadius: BorderRadius.circular(13.0),
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.all(widget.innerPadding),
                    child: Container(
                      height: innerHeight,
                      decoration: BoxDecoration(
                        color: Styles.emptyBarGrey,
                        borderRadius: BorderRadius.circular(12.0),
                      ),
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.all(widget.innerPadding),
                    child: SizedBox(
                      height: innerHeight,
                      child: AnimatedFractionallySizedBox(
                        curve: Curves.easeOutSine,
                        heightFactor: 1.0,
                        widthFactor: min(1.0, max(0.08, percentSpent)),
                        duration: const Duration(milliseconds: 350),
                        child: Container(
                          decoration: BoxDecoration(
                            color: widget.budgetCategory.color,
                            borderRadius: BorderRadius.circular(12.0),
                          ),
                        ),
                      ),
                    ),
                  ),
                  SizedBox(
                    height: widget.height,
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Center(
                          child: Padding(
                            padding: const EdgeInsets.only(left: 8.0),
                            child: Text(
                                '${widget.currentAmount.currency()} / ${widget.budgetCategory.amount.currency()}',
                                style: textStyle),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ))
          ],
        ),
      ),
    );
  }

  String formatBudgetName(String name) {
    if (name.length < 12) {
      return name;
    }
    if (!name.contains(' ') || name.indexOf(' ') == name.length - 1) {
      return name;
    }
    printLime('here');
    final words = name.split(' ');
    int index = 0;
    String firstLine = words[index];
    while (true) {
      index += 1;
      if (index == words.length) {
        return '$firstLine\n${words.sublist(index).join(' ')}';
      }
      if (firstLine.length + words[index].length > 12) {
        return '$firstLine\n${words.sublist(index).join(' ')}';
      }
      firstLine += ' ${words[index]}';
    }
  }
}
