import 'package:design_system/design_system.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import '../../domain/ui_entities/coverage_entities.dart';

/// List of shifts with their workers.
///
/// Displays all shifts for the selected date, or an empty state if none exist.
class CoverageShiftList extends StatelessWidget {
  /// Creates a [CoverageShiftList].
  const CoverageShiftList({
    required this.shifts,
    super.key,
  });

  /// The list of shifts to display.
  final List<CoverageShift> shifts;

  /// Formats a time string (HH:mm) to a readable format (h:mm a).
  String _formatTime(String? time) {
    if (time == null) return '';
    final List<String> parts = time.split(':');
    final DateTime dt = DateTime(
      2022,
      1,
      1,
      int.parse(parts[0]),
      int.parse(parts[1]),
    );
    return DateFormat('h:mm a').format(dt);
  }

  @override
  Widget build(BuildContext context) {
    if (shifts.isEmpty) {
      return Container(
        padding: const EdgeInsets.all(UiConstants.space8),
        width: double.infinity,
        decoration: BoxDecoration(
          color: UiColors.bgPopup,
          borderRadius: UiConstants.radiusLg,
          border: Border.all(color: UiColors.border),
        ),
        child: Column(
          spacing: UiConstants.space4,
          children: <Widget>[
            const Icon(
              UiIcons.users,
              size: UiConstants.space12,
              color: UiColors.textSecondary,
            ),
            Text(
              'No shifts scheduled for this day',
              style: UiTypography.body2r.textSecondary,
            ),
          ],
        ),
      );
    }

    return Column(
      children: shifts.map((CoverageShift shift) {
        return Container(
          margin: const EdgeInsets.only(bottom: UiConstants.space3),
          decoration: BoxDecoration(
            color: UiColors.bgPopup,
            borderRadius: UiConstants.radiusLg,
            border: Border.all(color: UiColors.border),
          ),
          clipBehavior: Clip.antiAlias,
          child: Column(
            children: <Widget>[
              _ShiftHeader(
                title: shift.title,
                location: shift.location,
                startTime: _formatTime(shift.startTime),
                current: shift.workers.length,
                total: shift.workersNeeded,
                coveragePercent: shift.coveragePercent,
              ),
              if (shift.workers.isNotEmpty)
                Padding(
                  padding: const EdgeInsets.all(UiConstants.space3),
                  child: Column(
                    children:
                        shift.workers.map<Widget>((CoverageWorker worker) {
                      final bool isLast = worker == shift.workers.last;
                      return Padding(
                        padding: EdgeInsets.only(
                          bottom: isLast ? 0 : UiConstants.space2,
                        ),
                        child: _WorkerRow(
                          worker: worker,
                          shiftStartTime: _formatTime(shift.startTime),
                          formatTime: _formatTime,
                        ),
                      );
                    }).toList(),
                  ),
                )
              else
                Padding(
                  padding: const EdgeInsets.all(UiConstants.space4),
                  child: Text(
                    'No workers assigned yet',
                    style: UiTypography.body3r.copyWith(
                      color: UiColors.mutedForeground,
                    ),
                  ),
                ),
            ],
          ),
        );
      }).toList(),
    );
  }
}

/// Header for a shift card.
class _ShiftHeader extends StatelessWidget {
  /// Creates a [_ShiftHeader].
  const _ShiftHeader({
    required this.title,
    required this.location,
    required this.startTime,
    required this.current,
    required this.total,
    required this.coveragePercent,
  });

  /// The shift title.
  final String title;

  /// The shift location.
  final String location;

  /// The shift start time.
  final String startTime;

  /// Current number of workers.
  final int current;

  /// Total workers needed.
  final int total;

  /// Coverage percentage.
  final int coveragePercent;

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(UiConstants.space4),
      decoration: const BoxDecoration(
        color: UiColors.muted,
        border: Border(
          bottom: BorderSide(
            color: UiColors.border,
          ),
        ),
      ),
      child: Row(
        spacing: UiConstants.space4,
        children: <Widget>[
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              spacing: UiConstants.space2,
              children: <Widget>[
                Row(
                  spacing: UiConstants.space2,
                  children: <Widget>[
                    Container(
                      width: UiConstants.space2,
                      height: UiConstants.space2,
                      decoration: const BoxDecoration(
                        color: UiColors.primary,
                        shape: BoxShape.circle,
                      ),
                    ),
                    Text(
                      title,
                      style: UiTypography.body1b.textPrimary,
                    ),
                  ],
                ),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Row(
                      spacing: UiConstants.space1,
                      children: <Widget>[
                        const Icon(
                          UiIcons.mapPin,
                          size: UiConstants.space3,
                          color: UiColors.iconSecondary,
                        ),
                        Expanded(child: Text(
                          location,
                          style: UiTypography.body3r.textSecondary,
                          overflow: TextOverflow.ellipsis,
                        )),
                      ],
                    ),
                    Row(
                      spacing: UiConstants.space1,
                      children: <Widget>[
                        const Icon(
                          UiIcons.clock,
                          size: UiConstants.space3,
                          color: UiColors.iconSecondary,
                        ),
                        Text(
                          startTime,
                          style: UiTypography.body3r.textSecondary,
                        ),
                      ],
                    ),
                  ],
                ),
              ],
            ),
          ),
          _CoverageBadge(
            current: current,
            total: total,
            coveragePercent: coveragePercent,
          ),
        ],
      ),
    );
  }
}

/// Coverage badge showing worker count and status.
class _CoverageBadge extends StatelessWidget {
  /// Creates a [_CoverageBadge].
  const _CoverageBadge({
    required this.current,
    required this.total,
    required this.coveragePercent,
  });

  /// Current number of workers.
  final int current;

  /// Total workers needed.
  final int total;

  /// Coverage percentage.
  final int coveragePercent;

  @override
  Widget build(BuildContext context) {
    Color bg;
    Color text;

    if (coveragePercent >= 100) {
      bg = UiColors.textSuccess;
      text = UiColors.primaryForeground;
    } else if (coveragePercent >= 80) {
      bg = UiColors.textWarning;
      text = UiColors.primaryForeground;
    } else {
      bg = UiColors.destructive;
      text = UiColors.destructiveForeground;
    }

    return Container(
      padding: const EdgeInsets.symmetric(
        horizontal: UiConstants.space2 + UiConstants.space1,
        vertical: UiConstants.space1 / 2,
      ),
      decoration: BoxDecoration(
        color: bg,
        borderRadius: UiConstants.radiusFull,
      ),
      child: Text(
        '$current/$total',
        style: UiTypography.body3m.copyWith(
          color: text,
        ),
      ),
    );
  }
}

/// Row displaying a single worker's status.
class _WorkerRow extends StatelessWidget {
  /// Creates a [_WorkerRow].
  const _WorkerRow({
    required this.worker,
    required this.shiftStartTime,
    required this.formatTime,
  });

  /// The worker to display.
  final CoverageWorker worker;

  /// The shift start time.
  final String shiftStartTime;

  /// Function to format time strings.
  final String Function(String?) formatTime;

  @override
  Widget build(BuildContext context) {
    Color bg;
    Color border;
    Color textBg;
    Color textColor;
    IconData icon;
    String statusText;
    Color badgeBg;
    Color badgeText;
    String badgeLabel;

    if (worker.isCheckedIn) {
      bg = UiColors.textSuccess.withOpacity(0.1);
      border = UiColors.textSuccess;
      textBg = UiColors.textSuccess.withOpacity(0.2);
      textColor = UiColors.textSuccess;
      icon = UiIcons.success;
      statusText = '✓ Checked In at ${formatTime(worker.checkInTime)}';
      badgeBg = UiColors.textSuccess;
      badgeText = UiColors.primaryForeground;
      badgeLabel = 'On Site';
    } else if (worker.isEnRoute) {
      bg = UiColors.textWarning.withOpacity(0.1);
      border = UiColors.textWarning;
      textBg = UiColors.textWarning.withOpacity(0.2);
      textColor = UiColors.textWarning;
      icon = UiIcons.clock;
      statusText = 'En Route - Expected $shiftStartTime';
      badgeBg = UiColors.textWarning;
      badgeText = UiColors.primaryForeground;
      badgeLabel = 'En Route';
    } else {
      bg = UiColors.destructive.withOpacity(0.1);
      border = UiColors.destructive;
      textBg = UiColors.destructive.withOpacity(0.2);
      textColor = UiColors.destructive;
      icon = UiIcons.warning;
      statusText = '⚠ Running Late';
      badgeBg = UiColors.destructive;
      badgeText = UiColors.destructiveForeground;
      badgeLabel = 'Late';
    }

    return Container(
      padding: const EdgeInsets.all(UiConstants.space2),
      decoration: BoxDecoration(
        color: bg,
        borderRadius: UiConstants.radiusMd,
      ),
      child: Row(
        children: <Widget>[
          Stack(
            clipBehavior: Clip.none,
            children: <Widget>[
              Container(
                width: UiConstants.space10,
                height: UiConstants.space10,
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  border: Border.all(color: border, width: 2),
                ),
                child: CircleAvatar(
                  backgroundColor: textBg,
                  child: Text(
                    worker.name.isNotEmpty ? worker.name[0] : 'W',
                    style: UiTypography.body1b.copyWith(
                      color: textColor,
                    ),
                  ),
                ),
              ),
              Positioned(
                bottom: -2,
                right: -2,
                child: Container(
                  width: UiConstants.space4,
                  height: UiConstants.space4,
                  decoration: BoxDecoration(
                    color: border,
                    shape: BoxShape.circle,
                  ),
                  child: Icon(
                    icon,
                    size: UiConstants.space2 + UiConstants.space1,
                    color: UiColors.primaryForeground,
                  ),
                ),
              ),
            ],
          ),
          const SizedBox(width: UiConstants.space3),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Text(
                  worker.name,
                  style: UiTypography.body2b.copyWith(
                    color: UiColors.textPrimary,
                  ),
                ),
                Text(
                  statusText,
                  style: UiTypography.body3m.copyWith(
                    color: textColor,
                  ),
                ),
              ],
            ),
          ),
          Container(
            padding: const EdgeInsets.symmetric(
              horizontal: UiConstants.space2,
              vertical: UiConstants.space1 / 2,
            ),
            decoration: BoxDecoration(
              color: badgeBg,
              borderRadius: UiConstants.radiusFull,
            ),
            child: Text(
              badgeLabel,
              style: UiTypography.footnote2b.copyWith(
                color: badgeText,
              ),
            ),
          ),
        ],
      ),
    );
  }
}
