import 'package:core_localization/core_localization.dart';
import 'package:design_system/design_system.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../domain/models/billing_period.dart';
import '../blocs/billing_bloc.dart';
import '../blocs/billing_state.dart';
import '../blocs/billing_event.dart';
import '../models/spending_breakdown_model.dart';

/// Card showing the spending breakdown for the current period.
class SpendingBreakdownCard extends StatefulWidget {
  /// Creates a [SpendingBreakdownCard].
  const SpendingBreakdownCard({super.key});

  @override
  State<SpendingBreakdownCard> createState() => _SpendingBreakdownCardState();
}

class _SpendingBreakdownCardState extends State<SpendingBreakdownCard>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<BillingBloc, BillingState>(
      builder: (BuildContext context, BillingState state) {
        final double total = state.spendingBreakdown.fold(
          0.0,
          (double sum, SpendingBreakdownItem item) => sum + item.amount,
        );

        return Container(
          padding: const EdgeInsets.all(UiConstants.space4),
          decoration: BoxDecoration(
            color: UiColors.white,
            borderRadius: UiConstants.radiusLg,
            border: Border.all(color: UiColors.border),
            boxShadow: <BoxShadow>[
              BoxShadow(
                color: UiColors.black.withValues(alpha: 0.04),
                blurRadius: 8,
                offset: const Offset(0, 2),
              ),
            ],
          ),
          child: Column(
            children: <Widget>[
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  Expanded(
                    child: Text(
                      t.client_billing.period_breakdown,
                      style: UiTypography.title2b.textPrimary,
                    ),
                  ),
                  const SizedBox(width: UiConstants.space2),
                  Container(
                    height: 32,
                    decoration: BoxDecoration(
                      color: UiColors.bgSecondary,
                      borderRadius: BorderRadius.circular(6),
                    ),
                    child: TabBar(
                      controller: _tabController,
                      isScrollable: true,
                      indicator: BoxDecoration(
                        color: UiColors.bgSecondary,
                        borderRadius: BorderRadius.circular(4),
                        boxShadow: <BoxShadow>[
                          BoxShadow(
                            color: UiColors.black.withValues(alpha: 0.05),
                            blurRadius: 1,
                          ),
                        ],
                      ),
                      labelColor: UiColors.textPrimary,
                      unselectedLabelColor: UiColors.textSecondary,
                      labelStyle: UiTypography.titleUppercase4b,
                      padding: const EdgeInsets.all(2),
                      indicatorSize: TabBarIndicatorSize.tab,
                      labelPadding: const EdgeInsets.symmetric(horizontal: 12),
                      dividerColor: Colors.transparent,
                      onTap: (int index) {
                        final BillingPeriod period =
                            index == 0 ? BillingPeriod.week : BillingPeriod.month;
                        context.read<BillingBloc>().add(
                              BillingPeriodChanged(period),
                            );
                      },
                      tabs: <Widget>[
                        Tab(text: t.client_billing.week),
                        Tab(text: t.client_billing.month),
                      ],
                    ),
                  ),
                ],
              ),
              const SizedBox(height: UiConstants.space4),
              ...state.spendingBreakdown.map(
                (SpendingBreakdownItem item) => _buildBreakdownRow(item),
              ),
              const Padding(
                padding: EdgeInsets.symmetric(vertical: UiConstants.space2),
                child: Divider(height: 1, color: UiColors.border),
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  Text(
                    t.client_billing.total,
                    style: UiTypography.body2b.textPrimary,
                  ),
                  Text(
                    '\$${total.toStringAsFixed(2)}',
                    style: UiTypography.body2b.textPrimary,
                  ),
                ],
              ),
            ],
          ),
        );
      },
    );
  }

  Widget _buildBreakdownRow(SpendingBreakdownItem item) {
    return Padding(
      padding: const EdgeInsets.only(bottom: UiConstants.space2),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Text(item.category, style: UiTypography.body2r.textPrimary),
                Text(
                  t.client_billing.hours(count: item.hours),
                  style: UiTypography.footnote2r.textSecondary,
                ),
              ],
            ),
          ),
          Text(
            '\$${item.amount.toStringAsFixed(2)}',
            style: UiTypography.body2m.textPrimary,
          ),
        ],
      ),
    );
  }
}
