// HACCP TempMon — Alerts screen
const { useState } = React;

function AlertsScreen({ activeAlerts, alertLog, selectedDevice, apiReachable }) {
  const [refreshing, setRefreshing] = useState(false);

  async function handleRefresh() {
    setRefreshing(true);
    await window.HACCP_STORE.refreshAlerts();
    setRefreshing(false);
  }

  const activeList = Object.values(activeAlerts);
  const CCP_COLORS = {
    COLD_CHAIN: 'var(--ccp-cold)',
    FREEZER:    'var(--ccp-freezer)',
    COOKING:    'var(--ccp-cooking)',
    HOT_HOLD:   'var(--ccp-hot-hold)',
    AMBIENT:    'var(--ccp-ambient)',
  };

  return (
    <div>
      {/* Header */}
      <div className="page-header">
        <div>
          <div className="page-eyebrow">CCP Monitoring</div>
          <h1 className="page-title">Alerts</h1>
          <div className="page-subtitle">
            {selectedDevice ? `Device: ${selectedDevice}` : 'No device selected'} ·{' '}
            {activeList.length > 0
              ? `${activeList.length} active breach${activeList.length > 1 ? 'es' : ''}`
              : 'No active breaches'}
          </div>
        </div>
        <button className="btn" onClick={handleRefresh} disabled={refreshing}>
          <Icon name="refresh" size={14} />
          {refreshing ? 'Refreshing…' : 'Refresh'}
        </button>
      </div>

      {/* Active breaches */}
      <div className="card" style={{ marginBottom: 24 }}>
        <div className="card-title">Active Breaches</div>
        {activeList.length === 0 ? (
          <div className="row items-center gap-8" style={{ padding: '16px 0', color: 'var(--status-safe)' }}>
            <Icon name="check-circle" size={18} />
            <span className="text-sm">All CCPs in range — no active breaches</span>
          </div>
        ) : (
          activeList.map(a => (
            <div key={a.alert_type} className="alert-item">
              <span className="alert-dot" />
              <div className="col gap-4" style={{ flex: 1 }}>
                <div className="row gap-8 items-center">
                  <span className="alert-type">{a.alert_type}</span>
                  {a.ccp_type && <CcpBadge ccpType={a.ccp_type} />}
                </div>
                <div className="text-xs text-ink-3">
                  Since {new Date(a.since).toLocaleTimeString('en-GB', { hour12: false })}
                </div>
              </div>
              <div className="col items-center gap-4" style={{ textAlign: 'right' }}>
                <span className="alert-temp">{formatTemp(a.temp_c)}</span>
                <span className="alert-threshold">limit {formatTemp(a.threshold_c)}</span>
              </div>
            </div>
          ))
        )}
      </div>

      {/* Alert history table */}
      <div className="card">
        <div className="card-title" style={{ marginBottom: 0 }}>Alert History</div>
        {!apiReachable && (
          <div className="text-xs text-ink-3" style={{ margin: '12px 0 0' }}>
            API offline — connect the backend to see historical alerts.
          </div>
        )}
        {apiReachable && alertLog.length === 0 && (
          <div className="text-sm text-ink-3" style={{ marginTop: 16, padding: '8px 0' }}>
            No alert history for this device.
          </div>
        )}
        {alertLog.length > 0 && (
          <table style={{ width: '100%', borderCollapse: 'collapse', marginTop: 16 }}>
            <thead>
              <tr>
                {['Time', 'Type', 'CCP', 'Temp', 'Threshold', 'Duration', 'Status'].map(h => (
                  <th key={h} style={{ textAlign: 'left', fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--ink-4)', padding: '0 12px 8px 0', fontWeight: 600 }}>
                    {h}
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {alertLog.map((a, i) => {
                const dur = a.duration_s != null
                  ? (a.duration_s < 60 ? `${a.duration_s}s` : `${Math.floor(a.duration_s / 60)}m`)
                  : '—';
                const resolved = a.resolved_at != null;
                const ccpColor = CCP_COLORS[a.ccp_type] || 'var(--ink-3)';
                return (
                  <tr key={a.id || i} style={{ borderTop: i > 0 ? '1px solid var(--line)' : 'none' }}>
                    <td style={{ padding: '10px 12px 10px 0', fontSize: 13 }}>
                      <span className="mono" style={{ fontSize: 12, color: 'var(--ink-3)' }}>
                        {formatTs(a.created_at)}
                      </span>
                    </td>
                    <td style={{ padding: '10px 12px 10px 0', fontSize: 13, fontWeight: 500 }}>
                      {a.alert_type}
                    </td>
                    <td style={{ padding: '10px 12px 10px 0' }}>
                      {a.ccp_type && (
                        <span style={{ fontSize: 11, fontWeight: 600, color: ccpColor }}>
                          {a.ccp_type}
                        </span>
                      )}
                    </td>
                    <td style={{ padding: '10px 12px 10px 0', fontFamily: 'var(--font-mono)', fontSize: 13, color: 'var(--status-breach)' }}>
                      {a.temp_c != null ? a.temp_c.toFixed(1) + '°C' : '—'}
                    </td>
                    <td style={{ padding: '10px 12px 10px 0', fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--ink-3)' }}>
                      {a.threshold_c != null ? a.threshold_c.toFixed(1) + '°C' : '—'}
                    </td>
                    <td style={{ padding: '10px 12px 10px 0', fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--ink-3)' }}>
                      {dur}
                    </td>
                    <td style={{ padding: '10px 0 10px 0' }}>
                      <span style={{
                        display: 'inline-flex', alignItems: 'center', gap: 4,
                        fontSize: 11, fontWeight: 600, padding: '2px 8px', borderRadius: 100,
                        background: resolved ? 'oklch(0.58 0.17 145 / 0.1)' : 'oklch(0.55 0.2 25 / 0.1)',
                        color: resolved ? 'var(--status-safe)' : 'var(--status-breach)',
                      }}>
                        {resolved ? 'Resolved' : 'Active'}
                      </span>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}
