import 'package:siro_driver/constant/currency.dart';
import 'package:flutter/material.dart';
import 'package:flutter_staggered_animations/flutter_staggered_animations.dart';
import 'package:get/get.dart';
import 'package:siro_driver/constant/finance_design_system.dart';
import 'package:siro_driver/views/widgets/mycircular.dart';
import '../../../controller/payment/driver_payment_controller.dart';
import 'widgets/transaction_preview_item.dart';

class WeeklyPaymentPage extends StatelessWidget {
  const WeeklyPaymentPage({super.key});

  @override
  Widget build(BuildContext context) {
    Get.put(DriverWalletHistoryController());

    return Scaffold(
      backgroundColor: FinanceDesignSystem.backgroundColor,
      appBar: AppBar(
        title: Text('Weekly Summary'.tr,
            style: TextStyle(
                fontWeight: FontWeight.bold,
                color: FinanceDesignSystem.primaryDark)),
        backgroundColor: Colors.transparent,
        elevation: 0,
        centerTitle: true,
        leading: IconButton(
          icon: Icon(Icons.arrow_back_ios_new_rounded,
              color: FinanceDesignSystem.primaryDark, size: 20),
          onPressed: () => Get.back(),
        ),
      ),
      body: GetBuilder<DriverWalletHistoryController>(
        builder: (controller) {
          if (controller.isLoading) {
            return const Center(child: MyCircularProgressIndicator());
          }

          return Column(
            children: [
              _buildWeeklyStatsHeader(controller),
              const SizedBox(height: 16),
              _buildWeekSelector(),
              const SizedBox(height: 16),
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 20),
                child: Row(
                  children: [
                    Text('Transactions this week'.tr,
                        style: FinanceDesignSystem.headingStyle),
                    const Spacer(),
                    Icon(Icons.list_rounded,
                        color: Colors.grey.shade400, size: 20),
                  ],
                ),
              ),
              const SizedBox(height: 8),
              Expanded(
                child: controller.weeklyList.isEmpty
                    ? _buildEmptyState(context)
                    : AnimationLimiter(
                        child: ListView.builder(
                          padding: const EdgeInsets.fromLTRB(16, 8, 16, 24),
                          itemCount: controller.weeklyList.length,
                          itemBuilder: (BuildContext context, int index) {
                            final tx = controller.weeklyList[index];
                            final double amount = double.tryParse(
                                    tx['amount']?.toString() ?? '0') ??
                                0;
                            return AnimationConfiguration.staggeredList(
                              position: index,
                              duration: const Duration(milliseconds: 250),
                              child: SlideAnimation(
                                verticalOffset: 25,
                                child: FadeInAnimation(
                                  child: TransactionPreviewItem(
                                    title:
                                        amount >= 0 ? 'Credit'.tr : 'Debit'.tr,
                                    subtitle: tx['dateUpdated'] ?? '',
                                    amount: amount.abs().toStringAsFixed(0),
                                    date:
                                        tx['dateUpdated']?.split(' ')[0] ?? '',
                                    type: amount >= 0 ? 'credit' : 'debit',
                                    method: tx['paymentMethod'],
                                    onTap: () {},
                                  ),
                                ),
                              ),
                            );
                          },
                        ),
                      ),
              ),
            ],
          );
        },
      ),
    );
  }

  Widget _buildWeeklyStatsHeader(DriverWalletHistoryController controller) {
    final totalAmount = controller.weeklyList.isEmpty
        ? '0.00'
        : controller.weeklyList[0]['totalAmount']?.toString() ?? '0.00';

    final double earnings = double.tryParse(totalAmount) ?? 0;
    final int trips = controller.weeklyList.length;
    final double commission = earnings * 0.15; // Example 15%
    final double netProfit = earnings - commission;

    return Container(
      margin: const EdgeInsets.all(16),
      padding: const EdgeInsets.all(24),
      decoration: BoxDecoration(
        gradient: FinanceDesignSystem.balanceGradient,
        borderRadius: BorderRadius.circular(24),
        boxShadow: [
          BoxShadow(
            color: FinanceDesignSystem.primaryDark.withValues(alpha: 0.3),
            blurRadius: 20,
            offset: const Offset(0, 8),
          ),
        ],
      ),
      child: Column(
        children: [
          Text('Total Weekly Earnings'.tr,
              style: TextStyle(
                  color: Colors.white.withValues(alpha: 0.8), fontSize: 14)),
          const SizedBox(height: 8),
          Text('${earnings.toStringAsFixed(0)} ${CurrencyHelper.currency}',
              style: const TextStyle(
                  color: Colors.white,
                  fontSize: 36,
                  fontWeight: FontWeight.bold)),
          const SizedBox(height: 24),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              _buildStatItem('Total Trips'.tr, trips.toString(),
                  Icons.directions_car_rounded),
              _buildStatItem('Commission'.tr, commission.toStringAsFixed(0),
                  Icons.percent_rounded),
              _buildStatItem('Net Profit'.tr, netProfit.toStringAsFixed(0),
                  Icons.account_balance_rounded),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildStatItem(String label, String value, IconData icon) {
    return Column(
      children: [
        Container(
          padding: const EdgeInsets.all(8),
          decoration: BoxDecoration(
              color: Colors.white.withValues(alpha: 0.1),
              borderRadius: BorderRadius.circular(10)),
          child: Icon(icon, color: Colors.white, size: 18),
        ),
        const SizedBox(height: 8),
        Text(value,
            style: const TextStyle(
                color: Colors.white,
                fontWeight: FontWeight.bold,
                fontSize: 14)),
        Text(label,
            style: TextStyle(
                color: Colors.white.withValues(alpha: 0.6), fontSize: 10)),
      ],
    );
  }

  Widget _buildWeekSelector() {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 16),
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(16),
          boxShadow: [
            BoxShadow(
                color: Colors.black.withValues(alpha: 0.02), blurRadius: 10)
          ],
        ),
        child: Row(
          children: [
            IconButton(
                icon: const Icon(Icons.chevron_left_rounded), onPressed: () {}),
            Expanded(
              child: Center(
                child: Text('Dec 15 - Dec 21, 2024'.tr,
                    style: TextStyle(
                        fontWeight: FontWeight.bold,
                        fontSize: 14,
                        color: FinanceDesignSystem.primaryDark)),
              ),
            ),
            IconButton(
                icon: const Icon(Icons.chevron_right_rounded),
                onPressed: () {}),
          ],
        ),
      ),
    );
  }

  Widget _buildEmptyState(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(Icons.bar_chart_rounded, size: 64, color: Colors.grey.shade300),
          const SizedBox(height: 16),
          Text('No transactions this week'.tr,
              style: const TextStyle(
                  fontWeight: FontWeight.bold, color: Colors.grey)),
        ],
      ),
    );
  }
}
