// HACCP TempMon — Monitoring periods / compliance log screen
const { useState } = React;

function HistoryScreen({ periods, selectedDevice, apiReachable }) {
  const [refreshing, setRefreshing] = useState(false);

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

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

  function fmtDuration(start, end) {
    if (!start || !end) return '—';
    const s = Math.round(end - start);
    if (s < 60)   return `${s}s`;
    if (s < 3600) return `${Math.floor(s / 60)}m`;
    const h = Math.floor(s / 3600);
    const m = Math.floor((s % 3600) / 60);
    return `${h}h ${m}m`;
  }

  return (
    <div>
      {/* Header */}
      <div className="page-header">
        <div>
          <div className="page-eyebrow">Compliance Record</div>
          <h1 className="page-title">Monitoring Log</h1>
          <div className="page-subtitle">
            {selectedDevice ? `Device: ${selectedDevice}` : 'No device selected'} ·{' '}
            {apiReachable === false ? 'API offline' : `${periods.length} period${periods.length !== 1 ? 's' : ''}`}
          </div>
        </div>
        <button className="btn" onClick={handleRefresh} disabled={refreshing}>
          <Icon name="refresh" size={14} />
          {refreshing ? 'Refreshing…' : 'Refresh'}
        </button>
      </div>

      {!apiReachable && (
        <div className="card" style={{ marginBottom: 24, padding: 20 }}>
          <div className="row gap-8 items-center text-ink-3">
            <Icon name="activity" size={16} />
            <span className="text-sm">
              Backend API is offline. Start the HACCP service with <span className="mono">--api</span> flag to see monitoring periods here.
            </span>
          </div>
        </div>
      )}

      {apiReachable && periods.length === 0 && (
        <div className="card" style={{ padding: 32, textAlign: 'center', color: 'var(--ink-3)' }}>
          <div style={{ marginBottom: 8 }}><Icon name="history" size={32} /></div>
          <div className="text-sm">No monitoring periods yet. Periods are created automatically when the service receives temperature readings.</div>
        </div>
      )}

      {periods.length > 0 && (
        <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead style={{ background: 'var(--bg-sunken)' }}>
              <tr>
                {['#', 'Device', 'CCP Type', 'Started', 'Duration', 'Readings', 'Min', 'Avg', 'Max', 'Breaches'].map(h => (
                  <th key={h} style={{
                    textAlign: 'left', fontSize: 11, textTransform: 'uppercase',
                    letterSpacing: '0.08em', color: 'var(--ink-4)',
                    padding: '12px 16px', fontWeight: 600,
                    borderBottom: '1px solid var(--line)',
                  }}>
                    {h}
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {periods.map((p, i) => {
                const ccpColor = CCP_COLORS[p.ccp_type] || 'var(--ink-3)';
                const hasBreach = p.breach_count > 0;
                return (
                  <tr key={p.id || i} style={{ borderTop: i > 0 ? '1px solid var(--line)' : 'none' }}>
                    <td style={{ padding: '12px 16px', fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--ink-4)' }}>
                      {p.id}
                    </td>
                    <td style={{ padding: '12px 16px', fontSize: 13, fontFamily: 'var(--font-mono)' }}>
                      {p.device_id}
                    </td>
                    <td style={{ padding: '12px 16px' }}>
                      <span style={{ fontSize: 12, fontWeight: 600, color: ccpColor }}>
                        {p.ccp_type || '—'}
                      </span>
                    </td>
                    <td style={{ padding: '12px 16px', fontSize: 12, fontFamily: 'var(--font-mono)', color: 'var(--ink-3)' }}>
                      {formatTs(p.started_at)}
                    </td>
                    <td style={{ padding: '12px 16px', fontSize: 12, fontFamily: 'var(--font-mono)', color: 'var(--ink-3)' }}>
                      {fmtDuration(p.started_at, p.ended_at || (Date.now() / 1000))}
                    </td>
                    <td style={{ padding: '12px 16px', fontFamily: 'var(--font-mono)', fontSize: 13 }}>
                      {p.reading_count ?? '—'}
                    </td>
                    <td style={{ padding: '12px 16px', fontFamily: 'var(--font-mono)', fontSize: 13, color: 'var(--ccp-freezer)' }}>
                      {p.min_temp_c != null ? p.min_temp_c.toFixed(1) + '°C' : '—'}
                    </td>
                    <td style={{ padding: '12px 16px', fontFamily: 'var(--font-mono)', fontSize: 13 }}>
                      {p.avg_temp_c != null ? p.avg_temp_c.toFixed(1) + '°C' : '—'}
                    </td>
                    <td style={{ padding: '12px 16px', fontFamily: 'var(--font-mono)', fontSize: 13, color: 'var(--ccp-cooking)' }}>
                      {p.max_temp_c != null ? p.max_temp_c.toFixed(1) + '°C' : '—'}
                    </td>
                    <td style={{ padding: '12px 16px' }}>
                      {hasBreach ? (
                        <span style={{
                          display: 'inline-flex', alignItems: 'center', gap: 4,
                          fontSize: 12, fontWeight: 600, padding: '2px 8px', borderRadius: 100,
                          background: 'oklch(0.55 0.2 25 / 0.1)', color: 'var(--status-breach)',
                        }}>
                          <Icon name="alert-triangle" size={11} />
                          {p.breach_count}
                        </span>
                      ) : (
                        <span style={{
                          display: 'inline-flex', alignItems: 'center', gap: 4,
                          fontSize: 12, fontWeight: 600, padding: '2px 8px', borderRadius: 100,
                          background: 'oklch(0.58 0.17 145 / 0.1)', color: 'var(--status-safe)',
                        }}>
                          <Icon name="check-circle" size={11} />
                          OK
                        </span>
                      )}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}
