import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_staggered_animations/flutter_staggered_animations.dart';
import 'package:get/get.dart';
import 'package:sefer_admin1/constant/colors.dart';
import 'package:sefer_admin1/controller/admin/dashboard_controller.dart';
import 'package:sefer_admin1/controller/admin/register_captain_controller.dart';
import 'package:sefer_admin1/controller/admin/static_controller.dart';
import 'package:sefer_admin1/controller/notification_controller.dart';
import 'package:sefer_admin1/main.dart';
import 'package:sefer_admin1/views/admin/captain/drivers_cant_registe.dart';
import 'package:sefer_admin1/views/widgets/mycircular.dart';

// Please make sure all these imports are correct for your project structure
import '../../constant/box_name.dart';
import '../../constant/links.dart';
import '../../constant/style.dart';
import '../../controller/functions/crud.dart';
import '../invoice/invoice_list_page.dart';
import '../widgets/my_scafold.dart';
import '../widgets/my_textField.dart';
import '../invoice/add_invoice_page.dart';
import 'captain/captain.dart';
import 'dashboard_widget.dart'; // Assuming DashboardStatCard is here
import 'drivers/driver_the_best.dart';
import 'employee/employee_page.dart';
import 'packages.dart';
import 'passenger/passenger.dart';
import 'rides/rides.dart';
import 'static/static.dart';
import 'wallet/wallet.dart';

class AdminHomePage extends StatelessWidget {
  AdminHomePage({super.key});

  // Responsive grid column calculation
  int _calculateCrossAxisCount(BuildContext context) {
    double screenWidth = MediaQuery.of(context).size.width;
    if (screenWidth > 1200) return 5; // Large desktops
    if (screenWidth > 900) return 4; // Desktops
    if (screenWidth > 600) return 3; // Tablets
    return 2; // Phones
  }

  // Helper to format currency
  String _formatCurrency(dynamic value) {
    if (value == null) return '\$0.00';
    final number = double.tryParse(value.toString());
    if (number != null) return '\$${number.toStringAsFixed(2)}';
    return '\$0.00';
  }

  final TextEditingController _messageController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    // Make sure DashboardController is initialized
    final DashboardController dashboardController =
        Get.put(DashboardController());

    // Action items list with Arabic titles
    final List<Map<String, dynamic>> actionItems = [
      {
        'title': 'الركاب',
        'icon': Icons.people_alt_outlined,
        'onPressed': () => Get.to(() => Passengrs(),
            transition: Transition.rightToLeftWithFade)
      },
      {
        'title': 'الكباتن',
        'icon': Icons.sports_motorsports_outlined,
        'onPressed': () =>
            Get.to(() => Captain(), transition: Transition.rightToLeftWithFade)
      },
      {
        'title': 'المحفظة',
        'icon': Icons.account_balance_wallet_outlined,
        'onPressed': () =>
            Get.to(() => Wallet(), transition: Transition.rightToLeftWithFade)
      },
      {
        'title': 'الرحلات',
        'icon': Icons.directions_car_filled_outlined,
        'onPressed': () =>
            Get.to(() => Rides(), transition: Transition.rightToLeftWithFade)
      },
      {
        'title': 'الإحصائيات',
        'icon': Icons.bar_chart_outlined,
        'onPressed': () async {
          await Get.put(StaticController()).getAll();
          Get.to(() => const StaticDash());
        }
      },
      {
        'title': 'إرسال واتساب للسائقين',
        'icon': Icons.message_outlined,
        'iconColor': Colors.green.shade600,
        'onPressed': () => _showWhatsAppDialog(context)
      },
      {
        'title': 'إرسال إشعار للسائقين',
        'icon': Icons.notifications_active_outlined,
        'onPressed': () async =>
            await Get.put(NotificationController()).getTokensDrivers()
      },
      {
        'title': 'إرسال إشعار للركاب',
        'icon': Icons.notification_important_outlined,
        'onPressed': () async =>
            await Get.put(NotificationController()).getTokensPassengers()
      },
      {
        'title': 'تسجيل كابتن جديد',
        'icon': Icons.person_add_alt_1_outlined,
        'onPressed': () async {
          await Get.put(RegisterCaptainController())
              .getDriverNotCompleteRegistration();
          Get.to(() => const DriversCantRegister());
        }
      },
      {
        'title': 'تحديث الباقات',
        'icon': Icons.inventory_2_outlined,
        'onPressed': () => Get.to(() => PackageUpdateScreen())
      },
      {
        'title': 'الموظفون',
        'icon': Icons.badge_outlined,
        'onPressed': () => Get.to(() => EmployeePage())
      },
      {
        'title': 'أفضل السائقين',
        'icon': Icons.star_border_purple500_outlined,
        'onPressed': () => Get.to(() => DriverTheBest())
      },
      {
        'title': 'إضافة فاتورة',
        'icon': Icons.post_add_outlined,
        // 'onPressed': () => Get.to(() => AddInvoicePage())
        'onPressed': () => Get.to(() => InvoiceListPage())
      },
      {
        'title': 'إضافة جهاز كمسؤول',
        'icon': Icons.admin_panel_settings_outlined,
        'onPressed': () async => await CRUD()
            .post(link: AppLink.addAdminUser, payload: {'name': 'b'})
      },
    ];

    return MyScafolld(
      title: 'لوحة التحكم الرئيسية',
      action: IconButton(
        onPressed: () async {
          await dashboardController.getDashBoard();
        },
        icon: const Icon(Icons.refresh, color: AppColor.primaryColor, size: 28),
        tooltip: 'تحديث',
      ),
      body: [
        GetBuilder<DashboardController>(builder: (controller) {
          if (controller.dashbord.isEmpty) {
            return const MyCircularProgressIndicator();
          }

          // Main data map for easier access
          final data = controller.dashbord[0];

          // Stat cards list with Arabic titles
          final List<Map<String, dynamic>> statCards = [
            {
              'title': 'رصيد الرسائل',
              'value': controller.creditSMS.toString(),
              'icon': Icons.sms_outlined,
              'color': Colors.lightBlue
            },
            {
              'title': 'الركاب',
              'value': data['countPassengers'].toString(),
              'icon': Icons.people_alt_outlined,
              'color': Colors.teal
            },
            {
              'title': 'السائقون',
              'value': data['countDriver'].toString(),
              'icon': Icons.sports_motorsports_outlined,
              'color': Colors.orange
            },
            {
              'title': 'رحلات الشهر',
              'value': data['countRideThisMonth'].toString(),
              'icon': Icons.calendar_month_outlined,
              'color': Colors.purple
            },
            {
              'title': 'متوسط التكلفة',
              'value': _formatCurrency(data['avg_passenger_price']),
              'icon': Icons.monetization_on_outlined,
              'color': Colors.green
            },
            {
              'title': 'الرحلات المكتملة',
              'value': data['completed_rides'].toString(),
              'icon': Icons.check_circle_outline,
              'color': AppColor.greenColor
            },
            {
              'title': 'الرحلات الملغاة',
              'value': data['cancelled_rides'].toString(),
              'icon': Icons.cancel_outlined,
              'color': AppColor.redColor
            },
            {
              'title': 'مدفوعات السائقين',
              'value': _formatCurrency(data['payments']),
              'icon': Icons.payments_outlined,
              'color': Colors.indigo
            },
            {
              'title': 'محفظة انطلق',
              'value': _formatCurrency(data['seferWallet']),
              'icon': Icons.account_balance_wallet_outlined,
              'color': Colors.deepOrange
            },
            {
              'title': 'عدد التحويلات',
              'value': data['transfer_from_count'].toString(),
              'icon': Icons.swap_horiz_outlined,
              'color': Colors.brown
            },
            {
              'title': 'رحلات الصباح',
              'value': data['morning_ride_count'].toString(),
              'icon': Icons.wb_sunny_outlined,
              'color': Colors.amber.shade700
            },
            {
              'title': 'رحلات المساء',
              'value': data['evening_ride_count'].toString(),
              'icon': Icons.brightness_4_outlined,
              'color': Colors.blueGrey
            },
            {
              'title': 'رحلات الليل',
              'value': data['night_ride_count'].toString(),
              'icon': Icons.nightlight_round_outlined,
              'color': Colors.black87
            },
            {
              'title': 'نوع كومفورت',
              'value': data['comfort'].toString(),
              'icon': Icons.event_seat_outlined,
              'color': Colors.cyan
            },
            {
              'title': 'نوع سبيد',
              'value': data['speed'].toString(),
              'icon': Icons.speed_outlined,
              'color': Colors.red.shade700
            },
            {
              'title': 'نوع ليدي',
              'value': data['lady'].toString(),
              'icon': Icons.woman_2_outlined,
              'color': Colors.pink
            },
          ];

          return AnimationLimiter(
            child: ListView(
              padding:
                  const EdgeInsets.symmetric(horizontal: 16.0, vertical: 10.0),
              children: [
                // --- Statistics Grid Section ---
                AnimationLimiter(
                  child: GridView.builder(
                    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: _calculateCrossAxisCount(context),
                      mainAxisSpacing: 12.0,
                      crossAxisSpacing: 12.0,
                      childAspectRatio: 1.8,
                    ),
                    itemCount: statCards.length,
                    shrinkWrap: true,
                    physics: const NeverScrollableScrollPhysics(),
                    itemBuilder: (context, index) {
                      final card = statCards[index];
                      return AnimationConfiguration.staggeredGrid(
                        position: index,
                        duration: const Duration(milliseconds: 375),
                        columnCount: _calculateCrossAxisCount(context),
                        child: ScaleAnimation(
                          child: FadeInAnimation(
                            child: DashboardStatCard(
                              title: card['title'] as String,
                              value: card['value'].toString(),
                              icon: card['icon'] as IconData,
                              iconColor: card['color'] as Color,
                              valueColor: (card['color'] as Color),
                            ),
                          ),
                        ),
                      );
                    },
                  ),
                ),

                const SizedBox(height: 20),
                Text("الإجراءات السريعة",
                    style: Theme.of(context)
                        .textTheme
                        .titleLarge
                        ?.copyWith(fontWeight: FontWeight.bold)),
                const SizedBox(height: 10),

                // --- Admin Actions List Section ---
                AnimationLimiter(
                  child: ListView.builder(
                    itemCount: actionItems.length,
                    shrinkWrap: true,
                    physics: const NeverScrollableScrollPhysics(),
                    itemBuilder: (context, index) {
                      final item = actionItems[index];
                      return AnimationConfiguration.staggeredList(
                        position: index,
                        duration: const Duration(milliseconds: 375),
                        child: SlideAnimation(
                          verticalOffset: 50.0,
                          child: FadeInAnimation(
                            child: AdminActionTile(
                              title: item['title'] as String,
                              icon: item['icon'] as IconData,
                              onPressed: item['onPressed'] as void Function(),
                              iconColor: item['iconColor'] as Color?,
                            ),
                          ),
                        ),
                      );
                    },
                  ),
                ),
              ],
            ),
          );
        }),
      ],
      isleading: false,
    );
  }

  void _showWhatsAppDialog(BuildContext context) {
    Get.dialog(
      AlertDialog(
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)),
        title: Text('تأكيد إرسال الرسائل؟'),
        content: MyTextForm(
          controller: _messageController,
          label: 'الرسالة',
          hint: 'أدخل نص الرسالة هنا',
          type: TextInputType.text,
        ),
        actions: [
          TextButton(
            onPressed: () {
              _messageController.clear();
              Get.back();
            },
            child: Text('إلغاء'),
          ),
          ElevatedButton(
            style: ElevatedButton.styleFrom(
                backgroundColor: AppColor.primaryColor),
            onPressed: () async {
              if (_messageController.text.isNotEmpty) {
                Get.back(); // Close dialog first
                var driverPhones =
                    box.read(BoxName.tokensDrivers)['message'] as List?;
                if (driverPhones == null || driverPhones.isEmpty) {
                  Get.snackbar('خطأ', 'لم يتم العثور على أرقام هواتف للسائقين.',
                      snackPosition: SnackPosition.BOTTOM);
                  return;
                }

                for (var driverData in driverPhones) {
                  if (driverData['phone'] != null) {
                    await CRUD().sendWhatsAppAuth(
                      driverData['phone'].toString(),
                      _messageController.text,
                    );
                    // Random delay to avoid being flagged as spam
                    await Future.delayed(
                        Duration(seconds: Random().nextInt(5) + 2));
                  }
                }
                _messageController.clear();
                Get.snackbar(
                  'نجاح',
                  'تم إرسال الرسائل بنجاح',
                  snackPosition: SnackPosition.BOTTOM,
                  backgroundColor: Colors.green.shade100,
                  colorText: Colors.black,
                );
              }
            },
            child: Text('إرسال', style: TextStyle(color: Colors.white)),
          ),
        ],
      ),
      barrierDismissible: false,
    );
  }
}

// Renamed for clarity and improved design
class AdminActionTile extends StatelessWidget {
  const AdminActionTile({
    super.key,
    required this.title,
    required this.onPressed,
    required this.icon,
    this.iconColor,
  });

  final String title;
  final VoidCallback onPressed;
  final IconData icon;
  final Color? iconColor;

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 6.0),
      child: Material(
        color: Theme.of(context).cardColor,
        borderRadius: BorderRadius.circular(12.0),
        child: InkWell(
          onTap: onPressed,
          borderRadius: BorderRadius.circular(12.0),
          child: Container(
            padding:
                const EdgeInsets.symmetric(horizontal: 16.0, vertical: 18.0),
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(12.0),
                border: Border.all(color: Colors.grey.withOpacity(0.2))),
            child: Row(
              children: [
                Icon(
                  icon,
                  size: 26,
                  color: iconColor ?? AppColor.primaryColor,
                ),
                const SizedBox(width: 16),
                Expanded(
                  child: Text(
                    title,
                    style: AppStyle.title.copyWith(
                      fontSize: 16,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ),
                const Icon(
                  Icons.arrow_forward_ios,
                  size: 16,
                  color: Colors.grey,
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
