/* global React, Card, StatusGlyph, Ic, Button, VS, LoadingState, ErrorState */

function ComputersScreen() {
  const [list, setList] = React.useState(null);
  const [err, setErr] = React.useState('');
  const [busyHost, setBusyHost] = React.useState('');
  const [confirmDelete, setConfirmDelete] = React.useState(null);
  const [, force] = React.useState(0);

  async function load() {
    try {
      const d = await VS.computers();
      setList(Array.isArray(d) ? d : (d.computers || []));
      setErr('');
    } catch (e) { setErr(e.message); }
  }

  React.useEffect(() => {
    load();
    const t = setInterval(load, 3000);
    const tick = setInterval(() => force(x => x + 1), 1000);
    return () => { clearInterval(t); clearInterval(tick); };
  }, []);

  async function restart(host) {
    setBusyHost(host);
    try { await VS.restartComputer(host); }
    catch (e) { setErr(e.message); }
    finally { setBusyHost(''); load(); }
  }

  async function remove(host) {
    setBusyHost(host);
    try { await VS.deleteComputer(host); setConfirmDelete(null); }
    catch (e) { setErr(e.message); }
    finally { setBusyHost(''); load(); }
  }

  if (err && !list) return <ErrorState message={err} />;
  if (!list) return <LoadingState />;

  return (
    <div style={{ padding: 24, maxWidth: 1200, margin: '0 auto', display: 'flex', flexDirection: 'column', gap: 16 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end' }}>
        <div>
          <div className="uppercase-label" style={{ marginBottom: 6 }}>Infrastruktura</div>
          <h1 style={{ margin: 0, fontSize: 24, fontWeight: 500, letterSpacing: '-0.02em' }}>Komputery klienckie</h1>
          <div style={{ fontSize: 12.5, color: 'var(--fg-muted)', marginTop: 6 }}>
            Stanowiska z agentem synchronizacji. Heartbeat co 10&nbsp;s, autoreset na zdalne polecenie.
          </div>
        </div>
        <Button icon={<Ic.refresh size={12} />} onClick={load}>Odśwież</Button>
      </div>

      {err && (
        <div style={{
          padding: '10px 12px', background: 'var(--alarm-weak)',
          border: '1px solid var(--alarm-border)', borderRadius: 'var(--r-sm)',
          color: 'var(--alarm)', fontSize: 12, fontFamily: 'var(--font-mono)',
        }}>{err}</div>
      )}

      {list.length === 0 && (
        <Card>
          <div style={{ textAlign: 'center', padding: '24px 16px', color: 'var(--fg-muted)' }}>
            <div className="uppercase-label" style={{ marginBottom: 6 }}>Brak komputerów</div>
            <div style={{ fontSize: 13 }}>Żaden agent nie zarejestrował jeszcze heartbeatu.</div>
          </div>
        </Card>
      )}

      {list.length > 0 && (
        <Card pad={false}>
          <div style={{
            display: 'grid', gridTemplateColumns: '32px 1.3fr 1fr 110px 90px 200px',
            padding: '10px 16px', borderBottom: '1px solid var(--hairline)',
            fontSize: 10, color: 'var(--fg-muted)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600,
          }}>
            <div></div>
            <div>Hostname</div>
            <div>Ostatni heartbeat</div>
            <div>Pomiarów</div>
            <div>Wersja</div>
            <div style={{ textAlign: 'right' }}>Akcje</div>
          </div>

          {list.map((c, i) => {
            const secAgo = effectiveSeconds(c);
            const online = secAgo !== null && secAgo < 30;
            const st = online ? 'ok' : (secAgo !== null && secAgo < 120 ? 'warn' : 'alarm');
            const pendingRestart = !!c.restart_requested;
            return (
              <div key={c.hostname || i} style={{
                display: 'grid', gridTemplateColumns: '32px 1.3fr 1fr 110px 90px 200px',
                padding: '14px 16px', borderBottom: i < list.length - 1 ? '1px solid var(--hairline)' : 'none',
                alignItems: 'center', fontSize: 12.5,
              }}>
                <StatusGlyph status={st} size={10} />
                <div>
                  <div style={{ fontWeight: 500 }}>{c.hostname}</div>
                  <div className="mono" style={{ fontSize: 10.5, color: 'var(--fg-subtle)', marginTop: 2 }}>
                    pid {c.pid || '—'}
                    {c.uptime_seconds ? <> · uptime {formatUptime(c.uptime_seconds)}</> : null}
                    {c.last_measid ? <> · measid {c.last_measid}</> : null}
                  </div>
                </div>
                <div>
                  <div className="mono" style={{ fontSize: 11.5, color: online ? 'var(--ok)' : (st === 'warn' ? 'var(--warn)' : 'var(--alarm)') }}>
                    {formatAgoLabel(secAgo)}
                  </div>
                  {c.last_error && (
                    <div style={{ fontSize: 10.5, color: 'var(--alarm)', marginTop: 2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: 280 }}
                      title={c.last_error}>
                      {c.last_error}
                    </div>
                  )}
                </div>
                <div className="mono" style={{ color: 'var(--fg-muted)' }}>{c.measurements_sent_total || 0}</div>
                <div className="mono" style={{ fontSize: 11, color: 'var(--fg-muted)' }}>{c.version || '—'}</div>
                <div style={{ display: 'flex', gap: 6, justifyContent: 'flex-end' }}>
                  {pendingRestart ? (
                    <span className="mono" style={{
                      fontSize: 10, color: 'var(--warn)', padding: '4px 8px',
                      border: '1px solid var(--border)', borderRadius: 2,
                      letterSpacing: '0.06em', textTransform: 'uppercase',
                    }}>restart pending</span>
                  ) : (
                    <Button size="sm" variant="ghost" icon={<Ic.refresh size={11} />}
                      disabled={busyHost === c.hostname}
                      onClick={() => restart(c.hostname)}>Restart</Button>
                  )}
                  <Button size="sm" variant="ghost"
                    disabled={busyHost === c.hostname}
                    onClick={() => setConfirmDelete(c.hostname)}>Usuń</Button>
                </div>
              </div>
            );
          })}
        </Card>
      )}

      {confirmDelete && (
        <div style={{
          position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.35)',
          display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 200,
        }} onClick={() => setConfirmDelete(null)}>
          <div onClick={(e) => e.stopPropagation()} style={{
            background: 'var(--surface)', border: '1px solid var(--border-strong)',
            borderRadius: 'var(--r-md)', padding: 20, width: 360,
          }}>
            <div style={{ fontSize: 14, fontWeight: 500, marginBottom: 8 }}>Usunąć wpis?</div>
            <div style={{ fontSize: 12.5, color: 'var(--fg-muted)', marginBottom: 16 }}>
              Usuniesz rekord <span className="mono">{confirmDelete}</span> z bazy. Jeśli agent nadal działa na tej maszynie, pojawi się ponownie po kolejnym heartbeacie.
            </div>
            <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
              <Button size="sm" variant="ghost" onClick={() => setConfirmDelete(null)}>Anuluj</Button>
              <Button size="sm" variant="accent" onClick={() => remove(confirmDelete)}>Usuń</Button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

function effectiveSeconds(c) {
  if (typeof c.seconds_ago === 'number') {
    const d = c.last_seen ? new Date(c.last_seen) : null;
    if (d && !isNaN(d.getTime())) {
      return Math.max(c.seconds_ago, Math.floor((Date.now() - d.getTime()) / 1000));
    }
    return c.seconds_ago;
  }
  if (c.last_seen) {
    const d = new Date(c.last_seen);
    if (!isNaN(d.getTime())) return Math.max(0, Math.floor((Date.now() - d.getTime()) / 1000));
  }
  return null;
}

function formatAgoLabel(secAgo) {
  if (secAgo === null || secAgo === undefined) return 'nigdy';
  if (secAgo < 60) return `${secAgo} s temu`;
  if (secAgo < 3600) return `${Math.floor(secAgo / 60)} min temu`;
  if (secAgo < 86400) return `${Math.floor(secAgo / 3600)} h temu`;
  return `${Math.floor(secAgo / 86400)} d temu`;
}

function formatUptime(sec) {
  if (!sec) return '0 s';
  if (sec < 60) return `${sec} s`;
  if (sec < 3600) return `${Math.floor(sec / 60)} min`;
  if (sec < 86400) return `${Math.floor(sec / 3600)} h`;
  return `${Math.floor(sec / 86400)} d`;
}

Object.assign(window, { ComputersScreen });
