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 {

  /// Creates a [CoverageDashboard].
  const CoverageDashboard({
    super.key,
    required this.shifts,
    required this.applications,
  });
  /// The list of shifts for today.
  final List<dynamic> shifts;

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

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

    for (final dynamic s in shifts) {
      final int needed = (s as Map<String, dynamic>)['workersNeeded'] as int? ?? 0;
      final int confirmed = s['filled'] as int? ?? 0;
      final double rate = s['hourlyRate'] as double? ?? 0.0;
      final double hours = s['hours'] as double? ?? 0.0;

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

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

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

    final bool isCoverageGood = coveragePercent >= 90;
    final Color coverageBadgeColor = isCoverageGood
        ? UiColors.tagSuccess
        : UiColors.tagPending;
    final Color coverageTextColor = isCoverageGood
        ? UiColors.textSuccess
        : UiColors.textWarning;

    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),
              if (totalNeeded > 0 || totalConfirmed > 0)
                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,
                    ),
                    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/$totalNeeded',
                      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 {

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

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

    if (isWarning) {
      bg = UiColors.tagPending;
      border = UiColors.borderStill;
      iconColor = UiColors.textWarning;
      textColor = UiColors.textWarning;
    } else if (isError) {
      bg = UiColors.tagError;
      border = UiColors.borderError;
      iconColor = UiColors.textError;
      textColor = UiColors.textError;
    } else if (isInfo) {
      bg = UiColors.tagInProgress;
      border = UiColors.primary.withValues(alpha: 0.2);
      iconColor = UiColors.primary;
      textColor = UiColors.primary;
    }

    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),
          ),
        ],
      ),
    );
  }
}
