import 'package:design_system/design_system.dart';
import 'package:flutter/material.dart';

/// A dashboard widget that displays today's coverage status.
class CoverageDashboard extends StatelessWidget {
  /// The list of shifts for today.
  final List<dynamic> shifts;

  /// The list of applications for today's shifts.
  final List<dynamic> applications;

  /// Creates a [CoverageDashboard].
  const CoverageDashboard({
    super.key,
    required this.shifts,
    required this.applications,
  });

  @override
  Widget build(BuildContext context) {
    int totalNeeded = 0;
    int totalConfirmed = 0;
    double todayCost = 0;

    for (final s in shifts) {
      final int needed = s['workersNeeded'] as int? ?? 0;
      final int confirmed = s['filled'] as int? ?? 0;
      final double rate = s['hourlyRate'] as double? ?? 20.0;

      totalNeeded += needed;
      totalConfirmed += confirmed;
      todayCost += rate * 8 * confirmed;
    }

    final int coveragePercent = totalNeeded > 0
        ? ((totalConfirmed / totalNeeded) * 100).round()
        : 100;
    final int unfilledPositions = totalNeeded - totalConfirmed;

    final int checkedInCount = applications
        .where((a) => (a as Map)['checkInTime'] != null)
        .length;
    final int lateWorkersCount = applications
        .where((a) => (a as Map)['status'] == 'LATE')
        .length;

    final bool isCoverageGood = coveragePercent >= 90;
    final Color coverageBadgeColor = isCoverageGood
        ? const Color(0xFFD1FAE5) // TODO: Use design system color if available
        : const Color(0xFFFEF3C7);
    final Color coverageTextColor = isCoverageGood
        ? const Color(0xFF047857)
        : const Color(0xFFB45309);

    return Container(
      padding: const EdgeInsets.all(UiConstants.space4),
      decoration: BoxDecoration(
        color: UiColors.white,
        borderRadius: UiConstants.radiusLg,
        border: Border.all(color: UiColors.border),
        boxShadow: <BoxShadow>[
          BoxShadow(
            color: UiColors.black.withValues(alpha: 0.02),
            blurRadius: 4,
            offset: const Offset(0, 1),
          ),
        ],
      ),
      child: Column(
        children: <Widget>[
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Text("Today's Status", style: UiTypography.body1m.textSecondary),
              Container(
                padding: const EdgeInsets.symmetric(
                  horizontal: UiConstants.space2,
                  vertical: 2.0,
                ),
                decoration: BoxDecoration(
                  color: coverageBadgeColor,
                  borderRadius: UiConstants.radiusMd,
                ),
                child: Text(
                  '$coveragePercent% Covered',
                  style: UiTypography.footnote1b.copyWith(
                    color: coverageTextColor,
                  ),
                ),
              ),
            ],
          ),
          const SizedBox(height: UiConstants.space4),

          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Expanded(
                child: Column(
                  children: <Widget>[
                    _StatusCard(
                      label: 'Unfilled Today',
                      value: '$unfilledPositions',
                      icon: UiIcons.warning,
                      isWarning: unfilledPositions > 0,
                    ),
                    if (lateWorkersCount > 0) ...<Widget>[
                      const SizedBox(height: UiConstants.space2),
                      _StatusCard(
                        label: 'Running Late',
                        value: '$lateWorkersCount',
                        icon: UiIcons.error,
                        isError: true,
                      ),
                    ],
                  ],
                ),
              ),
              const SizedBox(width: UiConstants.space2),
              Expanded(
                child: Column(
                  children: <Widget>[
                    _StatusCard(
                      label: 'Checked In',
                      value: '$checkedInCount/$totalConfirmed',
                      icon: UiIcons.success,
                      isInfo: true,
                    ),
                    const SizedBox(height: UiConstants.space2),
                    _StatusCard(
                      label: "Today's Cost",
                      value: '\$${todayCost.round()}',
                      icon: UiIcons.dollar,
                      isInfo: true,
                    ),
                  ],
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }
}

class _StatusCard extends StatelessWidget {
  final String label;
  final String value;
  final IconData icon;
  final bool isWarning;
  final bool isError;
  final bool isInfo;

  const _StatusCard({
    required this.label,
    required this.value,
    required this.icon,
    this.isWarning = false,
    this.isError = false,
    this.isInfo = false,
  });

  @override
  Widget build(BuildContext context) {
    Color bg = const Color(0xFFF1F5F9);
    Color border = const Color(0xFFE2E8F0);
    Color iconColor = UiColors.iconSecondary;
    Color textColor = UiColors.textPrimary;

    if (isWarning) {
      bg = const Color(0xFFFFFBEB);
      border = const Color(0xFFFDE68A);
      iconColor = const Color(0xFFD97706);
      textColor = const Color(0xFFB45309);
    } else if (isError) {
      bg = const Color(0xFFFEF2F2);
      border = const Color(0xFFFECACA);
      iconColor = const Color(0xFFDC2626);
      textColor = const Color(0xFFB91C1C);
    } else if (isInfo) {
      bg = const Color(0xFFEFF6FF);
      border = const Color(0xFFBFDBFE);
      iconColor = const Color(0xFF2563EB);
      textColor = const Color(0xFF1D4ED8);
    }

    return Container(
      padding: const EdgeInsets.all(UiConstants.space3),
      decoration: BoxDecoration(
        color: bg,
        border: Border.all(color: border),
        borderRadius: UiConstants.radiusMd,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Row(
            children: <Widget>[
              Icon(icon, size: 16, color: iconColor),
              const SizedBox(width: UiConstants.space2),
              Expanded(
                child: Text(
                  label,
                  style: UiTypography.footnote1m.copyWith(
                    color: textColor.withValues(alpha: 0.8),
                  ),
                  overflow: TextOverflow.ellipsis,
                ),
              ),
            ],
          ),
          const SizedBox(height: UiConstants.space1),
          Text(
            value,
            style: UiTypography.headline3m.copyWith(color: textColor),
          ),
        ],
      ),
    );
  }
}
