import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_modular/flutter_modular.dart';
import 'package:lucide_icons/lucide_icons.dart';
import 'package:intl/intl.dart';
import 'package:krow_domain/krow_domain.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';

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) {
    return BlocProvider<PaymentsBloc>.value(
      value: _bloc,
      child: Scaffold(
        backgroundColor: const Color(0xFFF8FAFC),
        body: BlocBuilder<PaymentsBloc, PaymentsState>(
          builder: (BuildContext context, PaymentsState state) {
            if (state is PaymentsLoading) {
              return const Center(child: CircularProgressIndicator());
            } else if (state is PaymentsError) {
              return Center(child: Text('Error: ${state.message}'));
            } 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: const BoxDecoration(
              gradient: LinearGradient(
                colors: <Color>[Color(0xFF0032A0), Color(0xFF333F48)],
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
              ),
            ),
            padding: EdgeInsets.fromLTRB(
              20,
              MediaQuery.of(context).padding.top + 24,
              20,
              32,
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                const Text(
                  "Earnings",
                  style: TextStyle(
                    fontSize: 20,
                    fontWeight: FontWeight.bold,
                    color: Colors.white,
                  ),
                ),
                const SizedBox(height: 24),

                // Main Balance
                Center(
                  child: Column(
                    children: <Widget>[
                      const Text(
                        "Total Earnings",
                        style: TextStyle(
                          color: Color(0xFFF8E08E),
                          fontSize: 14,
                        ),
                      ),
                      const SizedBox(height: 4),
                      Text(
                        "\$${state.summary.totalEarnings.toStringAsFixed(0).replaceAllMapped(RegExp(r'(\d{1,3})(?=(\d{3})+(?!\d))'), (Match m) => '${m[1]},')}",
                        style: const TextStyle(
                          fontSize: 36,
                          fontWeight: FontWeight.bold,
                          color: Colors.white,
                        ),
                      ),
                    ],
                  ),
                ),
                const SizedBox(height: 16),

                // Period Tabs
                Container(
                  padding: const EdgeInsets.all(4),
                  decoration: BoxDecoration(
                    color: Colors.white.withOpacity(0.2),
                    borderRadius: BorderRadius.circular(12),
                  ),
                  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, -16),
            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 20),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  // Quick Stats
                  Row(
                    children: <Widget>[
                      Expanded(
                        child: PaymentStatsCard(
                          icon: LucideIcons.trendingUp,
                          iconColor: const Color(0xFF059669),
                          label: "This Week",
                          amount: "\$${state.summary.weeklyEarnings}",
                        ),
                      ),
                      const SizedBox(width: 12),
                      Expanded(
                        child: PaymentStatsCard(
                          icon: LucideIcons.calendar,
                          iconColor: const Color(0xFF2563EB),
                          label: "This Month",
                          amount: "\$${state.summary.monthlyEarnings.toStringAsFixed(0)}",
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 16),

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

                  // Recent Payments
                  const Text(
                    "Recent Payments",
                    style: TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.w600,
                      color: Color(0xFF0F172A),
                    ),
                  ),
                  const SizedBox(height: 12),
                  Column(
                    children: state.history.map((StaffPayment payment) {
                      return Padding(
                        padding: const EdgeInsets.only(bottom: 8),
                        child: PaymentHistoryItem(
                          amount: payment.amount,
                          title: 'Assignment ${payment.assignmentId}',
                          location: 'Location', // TODO: Fetch from assignment
                          address: '',
                          date: payment.paidAt != null ? DateFormat('E, MMM d').format(payment.paidAt!) : 'Pending',
                          workedTime: '00:00 - 00:00', // TODO: Fetch from assignment
                          hours: 0,
                          rate: 0,
                          status: payment.status.toString().split('.').last,
                        ),
                      );
                    }).toList(),
                  ),
                  const SizedBox(height: 16),

                  // Export History Button
                  SizedBox(
                    width: double.infinity,
                    height: 48,
                    child: OutlinedButton.icon(
                      onPressed: () {
                        ScaffoldMessenger.of(context).showSnackBar(
                          const SnackBar(
                            content: Text('PDF Exported'),
                            duration: Duration(seconds: 2),
                          ),
                        );
                      },
                      icon: const Icon(LucideIcons.download, size: 16),
                      label: const Text("Export History"),
                      style: OutlinedButton.styleFrom(
                        foregroundColor: const Color(0xFF0F172A),
                        side: const BorderSide(color: Color(0xFFE2E8F0)),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(12),
                        ),
                      ),
                    ),
                  ),
                  const SizedBox(height: 32),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  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: 8),
          decoration: BoxDecoration(
            color: isSelected ? Colors.white : Colors.transparent,
            borderRadius: BorderRadius.circular(8),
          ),
          child: Center(
            child: Text(
              label,
              style: TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.w500,
                color: isSelected ? const Color(0xFF0032A0) : Colors.white,
              ),
            ),
          ),
        ),
      ),
    );
  }
}

