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 'package:flutter_modular/flutter_modular.dart';

import '../blocs/billing_bloc.dart';
import '../blocs/billing_event.dart';
import '../blocs/billing_state.dart';
import '../widgets/invoice_history_section.dart';
import '../widgets/payment_method_card.dart';
import '../widgets/pending_invoices_section.dart';
import '../widgets/spending_breakdown_card.dart';

/// The entry point page for the client billing feature.
///
/// This page initializes the [BillingBloc] and provides it to the [BillingView].
class BillingPage extends StatelessWidget {
  /// Creates a [BillingPage].
  const BillingPage({super.key});

  @override
  Widget build(BuildContext context) {
    return BlocProvider<BillingBloc>(
      create: (BuildContext context) =>
          Modular.get<BillingBloc>()..add(const BillingLoadStarted()),
      child: const BillingView(),
    );
  }
}

/// The main view for the client billing feature.
///
/// This widget displays the billing dashboard content based on the current
/// state of the [BillingBloc].
class BillingView extends StatefulWidget {
  /// Creates a [BillingView].
  const BillingView({super.key});

  @override
  State<BillingView> createState() => _BillingViewState();
}

class _BillingViewState extends State<BillingView> {
  late ScrollController _scrollController;
  bool _isScrolled = false;

  @override
  void initState() {
    super.initState();
    _scrollController = ScrollController();
    _scrollController.addListener(_onScroll);
  }

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

  void _onScroll() {
    if (_scrollController.hasClients) {
      if (_scrollController.offset > 140 && !_isScrolled) {
        setState(() => _isScrolled = true);
      } else if (_scrollController.offset <= 140 && _isScrolled) {
        setState(() => _isScrolled = false);
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<BillingBloc, BillingState>(
      builder: (BuildContext context, BillingState state) {
        return Scaffold(
          body: CustomScrollView(
            controller: _scrollController,
            slivers: <Widget>[
              SliverAppBar(
                pinned: true,
                expandedHeight: 200.0,
                backgroundColor: UiColors.primary,
                leading: Center(
                  child: UiIconButton.secondary(
                    icon: UiIcons.arrowLeft,
                    onTap: () => Modular.to.navigate('/client-main/home/'),
                  ),
                ),
                title: AnimatedSwitcher(
                  duration: const Duration(milliseconds: 200),
                  child: Text(
                    _isScrolled
                        ? '\$${state.currentBill.toStringAsFixed(2)}'
                        : t.client_billing.title,
                    key: ValueKey<bool>(_isScrolled),
                    style: UiTypography.headline4m.copyWith(
                      color: UiColors.white,
                    ),
                  ),
                ),
                flexibleSpace: FlexibleSpaceBar(
                  background: Padding(
                    padding: const EdgeInsets.only(
                      top: UiConstants.space0,
                      left: UiConstants.space5,
                      right: UiConstants.space5,
                      bottom: UiConstants.space10,
                    ),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: <Widget>[
                        Text(
                          t.client_billing.current_period,
                          style: UiTypography.footnote2r.copyWith(
                            color: UiColors.white.withValues(alpha: 0.7),
                          ),
                        ),
                        const SizedBox(height: UiConstants.space1),
                        Text(
                          '\$${state.currentBill.toStringAsFixed(2)}',
                          style: UiTypography.display1b
                              .copyWith(color: UiColors.white),
                        ),
                        const SizedBox(height: UiConstants.space2),
                        Container(
                          padding: const EdgeInsets.symmetric(
                            horizontal: UiConstants.space2,
                            vertical: UiConstants.space1,
                          ),
                          decoration: BoxDecoration(
                            color: UiColors.accent,
                            borderRadius: BorderRadius.circular(100),
                          ),
                          child: Row(
                            mainAxisSize: MainAxisSize.min,
                            children: <Widget>[
                              const Icon(
                                UiIcons.trendingDown,
                                size: 12,
                                color: UiColors.foreground,
                              ),
                              const SizedBox(width: UiConstants.space1),
                              Text(
                                t.client_billing.saved_amount(
                                  amount: state.savings.toStringAsFixed(0),
                                ),
                                style: UiTypography.footnote2b.copyWith(
                                  color: UiColors.foreground,
                                ),
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
              SliverList(
                delegate: SliverChildListDelegate(
                  <Widget>[
                    _buildContent(context, state),
                  ],
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  Widget _buildContent(BuildContext context, BillingState state) {
    if (state.status == BillingStatus.loading) {
      return const Padding(
        padding: EdgeInsets.all(UiConstants.space10),
        child: Center(child: CircularProgressIndicator()),
      );
    }

    if (state.status == BillingStatus.failure) {
      return Center(
        child: Text(
          state.errorMessage ?? 'An error occurred',
          style: UiTypography.body1r.textError,
        ),
      );
    }

    return Padding(
      padding: const EdgeInsets.all(UiConstants.space5),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        spacing: UiConstants.space4,
        children: <Widget>[
          if (state.pendingInvoices.isNotEmpty) ...<Widget>[
            PendingInvoicesSection(invoices: state.pendingInvoices),
          ],
          const PaymentMethodCard(),
          const SpendingBreakdownCard(),
          if (state.invoiceHistory.isEmpty) _buildEmptyState(context)
          else InvoiceHistorySection(invoices: state.invoiceHistory),
        ],
      ),
    );
  }

  Widget _buildEmptyState(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          const SizedBox(height: UiConstants.space12),
          Container(
            padding: const EdgeInsets.all(UiConstants.space6),
            decoration: BoxDecoration(
              color: UiColors.bgPopup,
              shape: BoxShape.circle,
              border: Border.all(color: UiColors.border),
            ),
            child: const Icon(
              UiIcons.file,
              size: 48,
              color: UiColors.textSecondary,
            ),
          ),
          const SizedBox(height: UiConstants.space4),
          Text(
            'No Invoices for the selected period',
            style: UiTypography.body1m.textSecondary,
            textAlign: TextAlign.center,
          ),
        ],
      ),
    );
  }
}
