// ================================================================
// frontend/src/components/dashboard/HealthStatusCard.tsx
// ================================================================
/**
 * Health Status Card - Top-level bakery status indicator
 *
 * Shows if the bakery is running smoothly (green), needs attention (yellow),
 * or has critical issues (red). This is the first thing users see.
 */

import React from 'react';
import { CheckCircle, AlertTriangle, AlertCircle, Clock, RefreshCw } from 'lucide-react';
import { BakeryHealthStatus } from '../../api/hooks/newDashboard';
import { formatDistanceToNow } from 'date-fns';
import { useTranslation } from 'react-i18next';

interface HealthStatusCardProps {
  healthStatus: BakeryHealthStatus;
  loading?: boolean;
}

const statusConfig = {
  green: {
    bgColor: 'var(--color-success-50)',
    borderColor: 'var(--color-success-200)',
    textColor: 'var(--color-success-800)',
    icon: CheckCircle,
    iconColor: 'var(--color-success-600)',
  },
  yellow: {
    bgColor: 'var(--color-warning-50)',
    borderColor: 'var(--color-warning-200)',
    textColor: 'var(--color-warning-900)',
    icon: AlertTriangle,
    iconColor: 'var(--color-warning-600)',
  },
  red: {
    bgColor: 'var(--color-error-50)',
    borderColor: 'var(--color-error-200)',
    textColor: 'var(--color-error-900)',
    icon: AlertCircle,
    iconColor: 'var(--color-error-600)',
  },
};

const iconMap = {
  check: CheckCircle,
  warning: AlertTriangle,
  alert: AlertCircle,
};

export function HealthStatusCard({ healthStatus, loading }: HealthStatusCardProps) {
  const { t } = useTranslation('reasoning');

  if (loading || !healthStatus) {
    return (
      <div className="animate-pulse rounded-lg shadow-md p-6" style={{ backgroundColor: 'var(--bg-primary)' }}>
        <div className="h-8 rounded w-3/4 mb-4" style={{ backgroundColor: 'var(--bg-tertiary)' }}></div>
        <div className="h-4 rounded w-1/2" style={{ backgroundColor: 'var(--bg-tertiary)' }}></div>
      </div>
    );
  }

  const status = healthStatus.status || 'green';
  const config = statusConfig[status];
  const StatusIcon = config.icon;

  return (
    <div
      className="border-2 rounded-xl p-6 shadow-lg transition-all duration-300 hover:shadow-xl"
      style={{
        backgroundColor: config.bgColor,
        borderColor: config.borderColor,
      }}
    >
      {/* Header with Status Icon */}
      <div className="flex items-start gap-4 mb-4">
        <div className="flex-shrink-0">
          <StatusIcon className="w-10 h-10 md:w-12 md:h-12" strokeWidth={2} style={{ color: config.iconColor }} />
        </div>
        <div className="flex-1 min-w-0">
          <h2 className="text-xl md:text-2xl font-bold mb-2" style={{ color: config.textColor }}>
            {healthStatus.headline || t(`jtbd.health_status.${status}`)}
          </h2>

          {/* Last Update */}
          <div className="flex items-center gap-2 text-sm" style={{ color: 'var(--text-secondary)' }}>
            <Clock className="w-4 h-4" />
            <span>
              {t('jtbd.health_status.last_updated')}:{' '}
              {healthStatus.lastOrchestrationRun
                ? formatDistanceToNow(new Date(healthStatus.lastOrchestrationRun), {
                    addSuffix: true,
                  })
                : t('jtbd.health_status.never')}
            </span>
          </div>

          {/* Next Check */}
          {healthStatus.nextScheduledRun && (
            <div className="flex items-center gap-2 text-sm mt-1" style={{ color: 'var(--text-secondary)' }}>
              <RefreshCw className="w-4 h-4" />
              <span>
                {t('jtbd.health_status.next_check')}:{' '}
                {formatDistanceToNow(new Date(healthStatus.nextScheduledRun), { addSuffix: true })}
              </span>
            </div>
          )}
        </div>
      </div>

      {/* Status Checklist */}
      {healthStatus.checklistItems && healthStatus.checklistItems.length > 0 && (
        <div className="space-y-3 mt-6">
          {healthStatus.checklistItems.map((item, index) => {
          const ItemIcon = iconMap[item.icon];
          const iconColor = item.actionRequired ? 'var(--color-warning-600)' : 'var(--color-success-600)';
          const bgColor = item.actionRequired ? 'var(--bg-primary)' : 'rgba(255, 255, 255, 0.5)';

          return (
            <div
              key={index}
              className="flex items-center gap-3 p-3 rounded-lg"
              style={{ backgroundColor: bgColor }}
            >
              <ItemIcon className="w-5 h-5 flex-shrink-0" style={{ color: iconColor }} />
              <span
                className={`text-sm md:text-base ${item.actionRequired ? 'font-semibold' : ''}`}
                style={{ color: 'var(--text-primary)' }}
              >
                {item.text || ''}
              </span>
            </div>
          );
        })}
      </div>
      )}

      {/* Summary Footer */}
      {(healthStatus.criticalIssues > 0 || healthStatus.pendingActions > 0) && (
        <div className="mt-6 pt-4" style={{ borderTop: '1px solid var(--border-primary)' }}>
          <div className="flex flex-wrap gap-4 text-sm">
            {healthStatus.criticalIssues > 0 && (
              <div className="flex items-center gap-2">
                <AlertCircle className="w-4 h-4" style={{ color: 'var(--color-error-600)' }} />
                <span className="font-semibold" style={{ color: 'var(--color-error-800)' }}>
                  {t('jtbd.health_status.critical_issues', { count: healthStatus.criticalIssues })}
                </span>
              </div>
            )}
            {healthStatus.pendingActions > 0 && (
              <div className="flex items-center gap-2">
                <AlertTriangle className="w-4 h-4" style={{ color: 'var(--color-warning-600)' }} />
                <span className="font-semibold" style={{ color: 'var(--color-warning-800)' }}>
                  {t('jtbd.health_status.actions_needed', { count: healthStatus.pendingActions })}
                </span>
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
}
