import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:siro_admin/constant/colors.dart';
import 'package:siro_admin/controller/admin/dashboard_v2_controller.dart';
import 'package:flutter_staggered_animations/flutter_staggered_animations.dart';

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

  @override
  Widget build(BuildContext context) {
    // Initialize controller
    final controller = Get.put(DashboardV2Controller());

    return GetBuilder<DashboardV2Controller>(
      builder: (ctrl) {
        if (ctrl.isLoading) {
          return const SliverToBoxAdapter(
            child: SizedBox(
              height: 150,
              child: Center(
                child: CircularProgressIndicator(color: AppColor.accent),
              ),
            ),
          );
        }

        return SliverToBoxAdapter(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 1. Real-time stats
              _buildSectionTitle('مركز العمليات الحي (Real-time)'),
              _buildRealtimeStats(ctrl.realtimeData),
              
              const SizedBox(height: 20),
              
              // 2. Smart Alerts
              if (ctrl.smartAlerts.isNotEmpty) ...[
                _buildSectionTitle('التنبيهات الذكية (${ctrl.smartAlerts.length})'),
                _buildSmartAlerts(ctrl.smartAlerts),
                const SizedBox(height: 10),
              ]
            ],
          ),
        );
      },
    );
  }

  Widget _buildSectionTitle(String title) {
    return Padding(
      padding: const EdgeInsets.fromLTRB(20, 8, 20, 10),
      child: Row(
        children: [
          Container(
            width: 3,
            height: 14,
            decoration: BoxDecoration(
              color: AppColor.danger, // Distinct color
              borderRadius: BorderRadius.circular(2),
            ),
          ),
          const SizedBox(width: 8),
          Text(
            title,
            style: const TextStyle(
              color: AppColor.textSecondary,
              fontSize: 12,
              fontWeight: FontWeight.bold,
              letterSpacing: 0.5,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildRealtimeStats(Map<String, dynamic> data) {
    final stats = [
      {
        'title': 'رحلات نشطة',
        'value': data['active_rides']?.toString() ?? '0',
        'icon': Icons.directions_car_rounded,
        'color': AppColor.info,
      },
      {
        'title': 'سائقون أونلاين',
        'value': data['online_drivers']?.toString() ?? '0',
        'icon': Icons.wifi_tethering,
        'color': AppColor.success,
      },
      {
        'title': 'إيرادات اليوم',
        'value': '${data['revenue_today'] ?? 0}',
        'icon': Icons.monetization_on_rounded,
        'color': AppColor.warning,
      },
      {
        'title': 'إيرادات الأمس',
        'value': '${data['revenue_yesterday'] ?? 0}',
        'icon': Icons.history_rounded,
        'color': Colors.grey,
      },
      {
        'title': 'شكاوى مفتوحة',
        'value': data['new_complaints']?.toString() ?? '0',
        'icon': Icons.warning_rounded,
        'color': AppColor.danger,
      },
      {
        'title': 'رخص تنتهي قريبًا',
        'value': data['expiring_licenses']?.toString() ?? '0',
        'icon': Icons.sd_card_alert_rounded,
        'color': Colors.orangeAccent,
      },
    ];

    return SizedBox(
      height: 110,
      child: ListView.builder(
        padding: const EdgeInsets.symmetric(horizontal: 16),
        scrollDirection: Axis.horizontal,
        itemCount: stats.length,
        itemBuilder: (ctx, i) {
          final stat = stats[i];
          return Padding(
            padding: const EdgeInsets.only(right: 10),
            child: _buildStatCard(stat),
          );
        },
      ),
    );
  }

  Widget _buildStatCard(Map<String, dynamic> stat) {
    final color = stat['color'] as Color;
    return Container(
      width: 140,
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: AppColor.surface,
        borderRadius: BorderRadius.circular(16),
        border: Border.all(color: color.withOpacity(0.3)),
        boxShadow: [
          BoxShadow(
            color: color.withOpacity(0.05),
            blurRadius: 10,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Row(
            children: [
              Container(
                padding: const EdgeInsets.all(6),
                decoration: BoxDecoration(
                  color: color.withOpacity(0.15),
                  borderRadius: BorderRadius.circular(8),
                ),
                child: Icon(stat['icon'] as IconData, color: color, size: 16),
              ),
              const Spacer(),
              // Pulsing indicator for active things
              if (stat['title'] == 'رحلات نشطة' || stat['title'] == 'سائقون أونلاين')
                Container(
                  width: 8,
                  height: 8,
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    color: color,
                    boxShadow: [
                      BoxShadow(
                        color: color.withOpacity(0.5),
                        blurRadius: 4,
                        spreadRadius: 1,
                      )
                    ]
                  ),
                ),
            ],
          ),
          const Spacer(),
          Text(
            stat['value'].toString(),
            style: const TextStyle(
              color: AppColor.textPrimary,
              fontSize: 20,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 2),
          Text(
            stat['title'].toString(),
            style: const TextStyle(
              color: AppColor.textSecondary,
              fontSize: 10,
              fontWeight: FontWeight.w500,
            ),
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
          ),
        ],
      ),
    );
  }

  Widget _buildSmartAlerts(List<dynamic> alerts) {
    return ListView.builder(
      padding: const EdgeInsets.symmetric(horizontal: 16),
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      itemCount: alerts.length > 5 ? 5 : alerts.length, // Show top 5
      itemBuilder: (context, index) {
        final alert = alerts[index];
        return AnimationConfiguration.staggeredList(
          position: index,
          duration: const Duration(milliseconds: 300),
          child: SlideAnimation(
            verticalOffset: 20.0,
            child: FadeInAnimation(
              child: _buildAlertItem(alert),
            ),
          ),
        );
      },
    );
  }

  Widget _buildAlertItem(Map<String, dynamic> alert) {
    Color getSeverityColor(String severity) {
      switch (severity) {
        case 'high':
          return AppColor.danger;
        case 'medium':
          return AppColor.warning;
        case 'warning':
          return Colors.orangeAccent;
        default:
          return AppColor.info;
      }
    }

    IconData getAlertIcon(String type) {
      switch (type) {
        case 'complaint':
          return Icons.report_problem_rounded;
        case 'ride':
          return Icons.directions_car_rounded;
        case 'license':
          return Icons.badge_rounded;
        default:
          return Icons.notifications_active_rounded;
      }
    }

    final color = getSeverityColor(alert['severity']);
    final icon = getAlertIcon(alert['type']);

    return Container(
      margin: const EdgeInsets.only(bottom: 10),
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: AppColor.surface,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: color.withOpacity(0.4)),
        boxShadow: [
          BoxShadow(
            color: color.withOpacity(0.05),
            blurRadius: 5,
            offset: const Offset(0, 2),
          )
        ],
      ),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            padding: const EdgeInsets.all(10),
            decoration: BoxDecoration(
              color: color.withOpacity(0.1),
              borderRadius: BorderRadius.circular(10),
            ),
            child: Icon(icon, color: color, size: 20),
          ),
          const SizedBox(width: 12),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  alert['title'] ?? '',
                  style: const TextStyle(
                    color: AppColor.textPrimary,
                    fontSize: 13,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const SizedBox(height: 4),
                Text(
                  alert['description'] ?? '',
                  style: const TextStyle(
                    color: AppColor.textSecondary,
                    fontSize: 11,
                  ),
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                ),
              ],
            ),
          ),
          const SizedBox(width: 8),
          Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              Text(
                alert['date'] != null
                    ? alert['date'].toString().split(' ')[0]
                    : '',
                style: const TextStyle(
                  color: AppColor.textSecondary,
                  fontSize: 10,
                ),
              ),
              const SizedBox(height: 10),
              Icon(Icons.arrow_forward_ios_rounded,
                  color: AppColor.textSecondary, size: 12),
            ],
          ),
        ],
      ),
    );
  }
}
