import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:flutter_staggered_animations/flutter_staggered_animations.dart';

import 'package:sefer_driver/constant/colors.dart';
import 'package:sefer_driver/constant/style.dart';
import 'package:sefer_driver/views/widgets/mycircular.dart';
import '../../../controller/payment/driver_payment_controller.dart';

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

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

    return Scaffold(
      appBar: AppBar(
        title: Text('Weekly Summary'.tr),
        backgroundColor: Colors.white,
        elevation: 1,
      ),
      backgroundColor: Colors.grey[100],
      body: GetBuilder<DriverWalletHistoryController>(
        builder: (controller) {
          if (controller.isLoading) {
            return const Center(child: MyCircularProgressIndicator());
          }

          return Column(
            children: [
              // 1. Prominent Summary Card at the top
              _buildSummaryCard(controller),

              // 2. A title for the transactions list
              Padding(
                padding: const EdgeInsets.fromLTRB(20, 20, 20, 10),
                child: Row(
                  children: [
                    Icon(Icons.list_alt, color: Colors.grey[600]),
                    const SizedBox(width: 8),
                    Text(
                      'Transactions this week'.tr,
                      style: Theme.of(context).textTheme.titleMedium?.copyWith(
                            fontWeight: FontWeight.bold,
                            color: Colors.grey[700],
                          ),
                    ),
                  ],
                ),
              ),

              // 3. The animated list of transactions
              Expanded(
                child: controller.weeklyList.isEmpty
                    ? _buildEmptyState(context)
                    : AnimationLimiter(
                        child: ListView.builder(
                          padding: const EdgeInsets.symmetric(horizontal: 16.0),
                          itemCount: controller.weeklyList.length,
                          itemBuilder: (BuildContext context, int index) {
                            var transaction = controller.weeklyList[index];
                            return AnimationConfiguration.staggeredList(
                              position: index,
                              duration: const Duration(milliseconds: 375),
                              child: SlideAnimation(
                                verticalOffset: 50.0,
                                child: FadeInAnimation(
                                  child: _TransactionListItem(
                                      transaction: transaction),
                                ),
                              ),
                            );
                          },
                        ),
                      ),
              ),
            ],
          );
        },
      ),
    );
  }

  // A widget for the top summary card.
  Widget _buildSummaryCard(DriverWalletHistoryController controller) {
    final String totalAmount = controller.weeklyList.isEmpty
        ? '0.00'
        : controller.weeklyList[0]['totalAmount']?.toString() ?? '0.00';

    return Card(
      margin: const EdgeInsets.all(16.0),
      elevation: 4,
      shadowColor: AppColor.primaryColor.withOpacity(0.2),
      clipBehavior: Clip.antiAlias,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)),
      child: Container(
        padding: const EdgeInsets.all(20.0),
        decoration: BoxDecoration(
          gradient: LinearGradient(
            colors: [AppColor.primaryColor, AppColor.greenColor],
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
          ),
        ),
        child: Row(
          children: [
            const Icon(Icons.account_balance_wallet,
                color: Colors.white, size: 40),
            const SizedBox(width: 16),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    'Total Weekly Earnings'.tr,
                    style: AppStyle.title
                        .copyWith(color: Colors.white70, fontSize: 16),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    '$totalAmount ${'SYP'.tr}',
                    style: AppStyle.number
                        .copyWith(color: Colors.white, fontSize: 32),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  // A dedicated widget for the list item.
  Widget _TransactionListItem({required Map<String, dynamic> transaction}) {
    final String paymentMethod = transaction['paymentMethod'] ?? 'Unknown';
    final String amount = transaction['amount']?.toString() ?? '0';
    final DateTime? date = DateTime.tryParse(transaction['dateUpdated'] ?? '');

    return Card(
      elevation: 2,
      shadowColor: Colors.black.withOpacity(0.05),
      margin: const EdgeInsets.only(bottom: 12.0),
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
      child: ListTile(
        leading: CircleAvatar(
          backgroundColor: AppColor.primaryColor.withOpacity(0.1),
          child: Icon(_getPaymentIcon(paymentMethod),
              color: AppColor.primaryColor, size: 22),
        ),
        title: Text(
          '$amount ${'SYP'.tr}',
          style: AppStyle.title.copyWith(fontWeight: FontWeight.bold),
        ),
        subtitle: Text(
          date != null
              ? DateFormat('EEEE, hh:mm a', Get.locale?.toString())
                  .format(date) // e.g., Tuesday, 10:11 AM
              : 'Invalid Date',
          style: AppStyle.title.copyWith(fontSize: 12, color: Colors.grey[600]),
        ),
        trailing: Chip(
          label: Text(
            _getTranslatedPaymentMethod(paymentMethod),
            style: const TextStyle(fontSize: 12, fontWeight: FontWeight.w600),
          ),
          backgroundColor: Colors.grey.shade200,
          padding: const EdgeInsets.symmetric(horizontal: 6),
          side: BorderSide.none,
        ),
      ),
    );
  }

  Widget _buildEmptyState(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(Icons.receipt_long_outlined, size: 80, color: Colors.grey[400]),
          const SizedBox(height: 16),
          Text(
            'No transactions this week'.tr,
            style: Theme.of(context)
                .textTheme
                .headlineSmall
                ?.copyWith(color: Colors.grey[600]),
          ),
        ],
      ),
    );
  }

  // Helper to get a specific icon for each payment method.
  IconData _getPaymentIcon(String paymentMethod) {
    switch (paymentMethod.toLowerCase()) {
      case 'visa':
        return Icons.credit_card;
      case 'frombudget':
        return Icons.account_balance_wallet_outlined;
      case 'remainder':
        return Icons.receipt_long;
      case 'cash':
        return Icons.money;
      default:
        return Icons.payment;
    }
  }

  // Helper to get translated or formatted payment method names.
  String _getTranslatedPaymentMethod(String paymentMethod) {
    switch (paymentMethod) {
      case 'Remainder':
        return 'Remainder'.tr;
      case 'fromBudget':
        return 'From Budget'.tr;
      default:
        return paymentMethod;
    }
  }
}
