import 'package:design_system/design_system.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_modular/flutter_modular.dart';
import 'package:intl/intl.dart';
import 'package:krow_domain/krow_domain.dart';
import 'package:core_localization/core_localization.dart';
import '../blocs/payments/payments_bloc.dart';
import '../blocs/payments/payments_event.dart';
import '../blocs/payments/payments_state.dart';
import '../widgets/payment_stats_card.dart';
import '../widgets/pending_pay_card.dart';
import '../widgets/payment_history_item.dart';
import '../widgets/earnings_graph.dart';

class PaymentsPage extends StatefulWidget {
  const PaymentsPage({super.key});

  @override
  State<PaymentsPage> createState() => _PaymentsPageState();
}

class _PaymentsPageState extends State<PaymentsPage> {
  final PaymentsBloc _bloc = Modular.get<PaymentsBloc>();

  @override
  void initState() {
    super.initState();
    _bloc.add(LoadPaymentsEvent());
  }

  @override
  Widget build(BuildContext context) {
    Translations.of(context);
    return BlocProvider<PaymentsBloc>.value(
      value: _bloc,
      child: Scaffold(
        backgroundColor: UiColors.background,
        body: BlocConsumer<PaymentsBloc, PaymentsState>(
          listener: (context, state) {
            // Error is already shown on the page itself (lines 53-63), no need for snackbar
          },
          builder: (BuildContext context, PaymentsState state) {
            if (state is PaymentsLoading) {
              return const Center(child: CircularProgressIndicator());

            } else if (state is PaymentsError) {
              return Center(
                child: Padding(
                  padding: const EdgeInsets.all(UiConstants.space4),
                  child: Text(
                    translateErrorKey(state.message),
                    textAlign: TextAlign.center,
                    style: UiTypography.body2r.copyWith(color: UiColors.textSecondary),
                  ),
                ),
              );
            } else if (state is PaymentsLoaded) {
              return _buildContent(context, state);
            }
            return const SizedBox.shrink();
          },
        ),
      ),
    );
  }

  Widget _buildContent(BuildContext context, PaymentsLoaded state) {
    return SingleChildScrollView(
      child: Column(
        children: <Widget>[
          // Header Section with Gradient
          Container(
            decoration: BoxDecoration(
              gradient: LinearGradient(
                colors: <Color>[
                  UiColors.primary,
                  UiColors.primary.withValues(alpha: 0.8),
                ],
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
              ),
            ),
            padding: EdgeInsets.fromLTRB(
              UiConstants.space5,
              MediaQuery.of(context).padding.top + UiConstants.space6,
              UiConstants.space5,
              UiConstants.space8,
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Text(
                  "Earnings",
                  style: UiTypography.displayMb.white,
                ),
                const SizedBox(height: UiConstants.space6),

                // Main Balance
                Center(
                  child: Column(
                    children: <Widget>[
                      Text(
                        "Total Earnings",
                        style: UiTypography.body2r.copyWith(
                          color: UiColors.accent,
                        ),
                      ),
                      const SizedBox(height: UiConstants.space1),
                      Text(
                        "\$${state.summary.totalEarnings.toStringAsFixed(0).replaceAllMapped(RegExp(r'(\d{1,3})(?=(\d{3})+(?!\d))'), (Match m) => '${m[1]},')}",
                        style: UiTypography.displayL.white,
                      ),
                    ],
                  ),
                ),
                const SizedBox(height: UiConstants.space4),

                // Period Tabs
                Container(
                  padding: const EdgeInsets.all(UiConstants.space1),
                  decoration: BoxDecoration(
                    color: UiColors.white.withValues(alpha: 0.2),
                    borderRadius: BorderRadius.circular(UiConstants.radiusBase),
                  ),
                  child: Row(
                    children: <Widget>[
                      _buildTab("Week", 'week', state.activePeriod),
                      _buildTab("Month", 'month', state.activePeriod),
                      _buildTab("Year", 'year', state.activePeriod),
                    ],
                  ),
                ),
              ],
            ),
          ),

          // Main Content - Offset upwards
          Transform.translate(
            offset: const Offset(0, -UiConstants.space4),
            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: UiConstants.space5),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  // Earnings Graph
                  EarningsGraph(
                    payments: state.history,
                    period: state.activePeriod,
                  ),
                  const SizedBox(height: UiConstants.space6),
                  // Quick Stats
                  Row(
                    children: <Widget>[
                      Expanded(
                        child: PaymentStatsCard(
                          icon: UiIcons.chart,
                          iconColor: UiColors.success,
                          label: "This Week",
                          amount: "\$${state.summary.weeklyEarnings}",
                        ),
                      ),
                      const SizedBox(width: UiConstants.space3),
                      Expanded(
                        child: PaymentStatsCard(
                          icon: UiIcons.calendar,
                          iconColor: UiColors.primary,
                          label: "This Month",
                          amount: "\$${state.summary.monthlyEarnings.toStringAsFixed(0)}",
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: UiConstants.space4),

                  // Pending Pay
                  if (state.summary.pendingEarnings > 0)
                    PendingPayCard(
                      amount: state.summary.pendingEarnings,
                      onCashOut: () {
                        Modular.to.pushNamed('/early-pay');
                      },
                    ),
                  const SizedBox(height: UiConstants.space6),

                  // Recent Payments
                  if (state.history.isNotEmpty)
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Text(
                          "Recent Payments",
                          style: UiTypography.body2m.textPrimary,
                        ),
                        const SizedBox(height: UiConstants.space3),
                        Column(
                          children: state.history.map((StaffPayment payment) {
                            return Padding(
                              padding: const EdgeInsets.only(
                                  bottom: UiConstants.space2),
                              child: PaymentHistoryItem(
                                amount: payment.amount,
                                title: "Shift Payment",
                                location: "Varies",
                                address: "Payment ID: ${payment.id}",
                                date: payment.paidAt != null
                                    ? DateFormat('E, MMM d')
                                        .format(payment.paidAt!)
                                    : 'Pending',
                                workedTime: "Completed",
                                hours: 0,
                                rate: 0.0,
                                status: payment.status.name.toUpperCase(),
                              ),
                            );
                          }).toList(),
                        ),
                      ],
                    ),

                  const SizedBox(height: UiConstants.space24),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildTab(String label, String value, String activePeriod) {
    final bool isSelected = activePeriod == value;
    return Expanded(
      child: GestureDetector(
        onTap: () => _bloc.add(ChangePeriodEvent(value)),
        child: Container(
          padding: const EdgeInsets.symmetric(vertical: UiConstants.space2),
          decoration: BoxDecoration(
            color: isSelected ? UiColors.white : UiColors.transparent,
            borderRadius: BorderRadius.circular(UiConstants.radiusMdValue),
          ),
          child: Center(
            child: Text(
              label,
              style: isSelected
                  ? UiTypography.body2m.copyWith(color: UiColors.primary)
                  : UiTypography.body2m.white,
            ),
          ),
        ),
      ),
    );
  }
}

