// BHEEM Sense — Alerts screen
//
// Every value here is rendered through its channel's unit, so a humidity
// breach reads as "82.0%" rather than being forced into a temperature column.
const { useState } = React;

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

  const debounceS = (profiles && profiles.debounce_s) || 30;

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

  async function handleClear(alertId) {
    if (alertId == null) return;
    if (!confirm(`Clear this alert? If the breach persists, it will re-alert after the ${debounceS}s confirmation window.`)) return;
    setClearingId(alertId);
    await window.BHEEM_STORE.clearAlert(alertId);
    setClearingId(null);
  }

  const activeList = Object.values(activeAlerts);

  const CHANNEL_LABEL = { temp: 'Temperature', rh: 'Humidity' };
  const CHANNEL_COLOR = { temp: 'var(--ccp-ambient)', rh: 'var(--ccp-cold)' };

  function ChannelTag({ channel }) {
    if (!channel) return null;
    const color = CHANNEL_COLOR[channel] || 'var(--ink-3)';
    return (
      <span style={{
        display: 'inline-flex', alignItems: 'center', gap: 5,
        padding: '2px 8px', borderRadius: 100,
        fontSize: 11, fontWeight: 600,
        background: color + '18', color,
      }}>
        {CHANNEL_LABEL[channel] || channel}
      </span>
    );
  }

  return (
    <div>
      {/* Header */}
      <div className="page-header">
        <div>
          <div className="page-eyebrow">Threshold 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">Temperature and humidity both in range</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>
                  <ChannelTag channel={a.channel} />
                  {a.profile && <ProfileBadge profile={a.profile} />}
                </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">{formatValue(a.value, a.unit)}</span>
                <span className="alert-threshold">limit {formatValue(a.threshold, a.unit)}</span>
              </div>
              {a.alert_id != null && (
                <button className="btn btn-sm" style={{ marginLeft: 12 }}
                  disabled={clearingId === a.alert_id}
                  onClick={() => handleClear(a.alert_id)}>
                  {clearingId === a.alert_id ? 'Clearing…' : 'Clear'}
                </button>
              )}
            </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 && (
          <div style={{ overflowX: 'auto' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse', marginTop: 16 }}>
              <thead>
                <tr>
                  {['Time', 'Type', 'Channel', 'Value', 'Limit', '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 ? `${Math.round(a.duration_s)}s` : `${Math.floor(a.duration_s / 60)}m`)
                    : '—';
                  const resolved = a.resolved_at != null;
                  const chColor = CHANNEL_COLOR[a.channel] || '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 }}>
                        {/* The alerts table column is `timestamp`; the HACCP original
                            read `created_at` here, which does not exist, so this
                            column was always blank. */}
                        <span className="mono" style={{ fontSize: 12, color: 'var(--ink-3)' }}>
                          {formatTs(a.timestamp)}
                        </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.channel && (
                          <span style={{ fontSize: 11, fontWeight: 600, color: chColor }}>
                            {CHANNEL_LABEL[a.channel] || a.channel}
                          </span>
                        )}
                      </td>
                      <td style={{ padding: '10px 12px 10px 0', fontFamily: 'var(--font-mono)', fontSize: 13, color: 'var(--status-breach)' }}>
                        {formatValue(a.value, a.unit)}
                      </td>
                      <td style={{ padding: '10px 12px 10px 0', fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--ink-3)' }}>
                        {formatValue(a.threshold, a.unit)}
                      </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>
                        {!resolved && a.id != null && (
                          <button className="btn btn-sm" style={{ marginLeft: 8 }}
                            disabled={clearingId === a.id}
                            onClick={() => handleClear(a.id)}>
                            {clearingId === a.id ? 'Clearing…' : 'Clear'}
                          </button>
                        )}
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}
