/* global React, Card, Button, Input, Ic, VS, Combobox, LoadingState, ErrorState */
// Protokoly osiowania — tworzenie, edycja, pobieranie PDF.
// 4 wartosci wpisuje uzytkownik (V, F1, A, F2), reszta ze skanowania lub manual.
// Przesun_max i rozw_max obliczane live w JS.

const OSIOWANIE_NORMS = [
  { rpm: 80,   pw: 1.60, pd: 0.80, rw: 1.00, rd: 0.80 },
  { rpm: 160,  pw: 0.80, pd: 0.40, rw: 0.50, rd: 0.40 },
  { rpm: 325,  pw: 0.40, pd: 0.20, rw: 0.26, rd: 0.20 },
  { rpm: 750,  pw: 0.19, pd: 0.09, rw: 0.13, rd: 0.09 },
  { rpm: 1500, pw: 0.09, pd: 0.06, rw: 0.07, rd: 0.05 },
  { rpm: 3000, pw: 0.06, pd: 0.03, rw: 0.04, rd: 0.03 },
  { rpm: 6000, pw: 0.03, pd: 0.02, rw: 0.03, rd: 0.02 },
];

function calcMaxPrzesun(v, a) {
  const vn = parseFloat(v), an = parseFloat(a);
  if (isNaN(vn) || isNaN(an)) return null;
  return Math.sqrt(vn * vn + an * an);
}

function calcMaxRozw(f1, f2) {
  const f1n = parseFloat(f1), f2n = parseFloat(f2);
  if (isNaN(f1n) || isNaN(f2n)) return null;
  return Math.sqrt(f1n * f1n + f2n * f2n);
}

function fmtNum(v, decimals = 3) {
  if (v === null || v === undefined) return '–';
  return v.toFixed(decimals);
}

function highlightRow(obr) {
  const n = parseInt(obr);
  if (!n) return -1;
  for (let i = 0; i < OSIOWANIE_NORMS.length; i++) {
    if (OSIOWANIE_NORMS[i].rpm >= n) return i;
  }
  return OSIOWANIE_NORMS.length - 1;
}

// ── Ekran listy protokołów ──
function OsiowanieScreen() {
  const [list, setList] = React.useState(null);
  const [err, setErr] = React.useState('');
  const [openId, setOpenId] = React.useState(null);
  const [creating, setCreating] = React.useState(false);

  const load = React.useCallback(() => {
    VS.request('GET', '/api/osiowanie')
      .then(r => setList(r))
      .catch(e => setErr(e.message));
  }, []);

  React.useEffect(() => { load(); }, [load]);

  async function newProtocol() {
    setCreating(true);
    try {
      const r = await VS.request('POST', '/api/osiowanie', { body: {} });
      setOpenId(r.id);
      load();
    } catch (e) { alert('Blad: ' + e.message); }
    finally { setCreating(false); }
  }

  async function deleteProtocol(id, name) {
    if (!confirm(`Usunac protokol "${name || id}"?`)) return;
    try { await VS.request('DELETE', `/api/osiowanie/${id}`); load(); }
    catch (e) { alert('Blad: ' + e.message); }
  }

  if (openId !== null) {
    return (
      <OsiowanieEditor id={openId} onBack={() => { setOpenId(null); load(); }} />
    );
  }

  return (
    <div style={{ padding: 24, maxWidth: 1100, margin: '0 auto', display: 'flex', flexDirection: 'column', gap: 16 }}>
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between' }}>
        <div>
          <div className="uppercase-label" style={{ marginBottom: 4 }}>Protokoly</div>
          <h1 style={{ margin: 0, fontSize: 24, fontWeight: 500, letterSpacing: '-0.02em' }}>Osiowanie</h1>
          <div style={{ fontSize: 12.5, color: 'var(--fg-muted)', marginTop: 4 }}>
            Protokoly pomiaru i wyregulowania osiowania.
          </div>
        </div>
        <Button variant="primary" icon={<Ic.plus size={12} />} onClick={newProtocol} disabled={creating}>
          {creating ? 'Tworze...' : 'Nowy protokol'}
        </Button>
      </div>

      {err && <div style={{ padding: 12, background: 'var(--alarm-weak)', border: '1px solid var(--alarm-border)', color: 'var(--alarm)', borderRadius: 'var(--r-sm)', fontSize: 12 }}>{err}</div>}
      {!list && !err && <div style={{ padding: 32, textAlign: 'center', color: 'var(--fg-muted)' }}>Ladowanie...</div>}
      {list && list.length === 0 && (
        <Card><div style={{ textAlign: 'center', padding: 32, color: 'var(--fg-muted)' }}>
          Brak protokolow. Kliknij „Nowy protokol" aby zaczac.
        </div></Card>
      )}
      {list && list.length > 0 && (
        <Card pad={false}>
          <div style={{
            display: 'grid', gridTemplateColumns: '140px 1fr 160px 140px 180px',
            gap: 10, padding: '10px 16px', borderBottom: '1px solid var(--hairline)',
            fontSize: 10, color: 'var(--fg-muted)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600,
          }}>
            <div>Nr protokolu</div>
            <div>Urzadzenie</div>
            <div>Zleceniodawca</div>
            <div>Data osiowania</div>
            <div>Akcje</div>
          </div>
          {list.map((p, i) => (
            <div key={p.id} style={{
              display: 'grid', gridTemplateColumns: '140px 1fr 160px 140px 180px',
              gap: 10, padding: '10px 16px',
              borderBottom: i < list.length - 1 ? '1px solid var(--hairline)' : 'none',
              alignItems: 'center', fontSize: 12.5,
            }}>
              <div className="mono" style={{ fontWeight: 500 }}>{p.nr_protokolu || <span style={{ color: 'var(--fg-subtle)' }}>—</span>}</div>
              <div style={{ fontWeight: p.machine_name ? 500 : 400, color: p.machine_name ? 'var(--fg)' : 'var(--fg-subtle)' }}>
                {p.machine_name || '(brak nazwy)'}
                {p.machine_code && <span className="mono" style={{ marginLeft: 8, fontSize: 11, color: 'var(--fg-muted)', background: 'var(--bg-sunken)', padding: '1px 5px', borderRadius: 3 }}>{p.machine_code}</span>}
              </div>
              <div style={{ color: 'var(--fg-muted)', fontSize: 11.5, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{p.zleceniodawca || '—'}</div>
              <div className="mono" style={{ fontSize: 11.5 }}>{p.data_osiowania || '—'}</div>
              <div style={{ display: 'flex', gap: 6 }}>
                <Button size="sm" icon={<Ic.edit size={11} />} onClick={() => setOpenId(p.id)}>Edytuj</Button>
                <Button size="sm" icon={<Ic.download size={11} />}
                  onClick={() => window.open(`/api/osiowanie/${p.id}/pdf?token=${VS.getToken()}`, '_blank')}>
                  PDF
                </Button>
                <Button size="sm" variant="danger" icon={<Ic.trash size={11} />} onClick={() => deleteProtocol(p.id, p.machine_name)}>
                  Usuń
                </Button>
              </div>
            </div>
          ))}
        </Card>
      )}
    </div>
  );
}

// ── Edytor protokolu ──
function OsiowanieEditor({ id, onBack }) {
  const [d, setD] = React.useState(null);
  const [users, setUsers] = React.useState([]);
  const [saving, setSaving] = React.useState(false);
  const [msg, setMsg] = React.useState('');
  const [err, setErr] = React.useState('');

  React.useEffect(() => {
    VS.request('GET', `/api/osiowanie/${id}`)
      .then(r => setD(r))
      .catch(e => setErr(e.message));
    VS.usersList()
      .then(setUsers)
      .catch(() => setUsers([]));
  }, [id]);

  function set(key, val) {
    setD(prev => ({ ...prev, [key]: val }));
  }

  async function save() {
    setSaving(true); setMsg('');
    try {
      await VS.request('PUT', `/api/osiowanie/${id}`, { body: d });
      setMsg('Zapisano.');
      setTimeout(() => setMsg(''), 2000);
    } catch (e) { setMsg('Blad: ' + e.message); }
    finally { setSaving(false); }
  }

  async function openPdf() {
    try {
      const r = await fetch(`/api/osiowanie/${id}/pdf`, {
        headers: { Authorization: `Bearer ${VS.getToken()}` },
      });
      if (!r.ok) { alert('Blad generowania PDF: ' + r.status); return; }
      const blob = await r.blob();
      const url = URL.createObjectURL(blob);
      window.open(url, '_blank');
      setTimeout(() => URL.revokeObjectURL(url), 60000);
    } catch (e) { alert('Blad: ' + e.message); }
  }

  if (err) return <div style={{ padding: 24 }}><Card><div style={{ color: 'var(--alarm)' }}>{err}</div></Card></div>;
  if (!d) return <div style={{ padding: 32, textAlign: 'center', color: 'var(--fg-muted)' }}>Ladowanie...</div>;

  const przesun = calcMaxPrzesun(d.v_pion, d.a_poziom);
  const rozw    = calcMaxRozw(d.f1_rozwarcie, d.f2_rozwarcie);
  const hiRow   = highlightRow(d.obr_min);

  const userOpts = users.map(u => ({
    value: String(u.id), label: u.display_name || u.username, hint: u.username,
  }));
  const userIdToName = Object.fromEntries(users.map(u => [String(u.id), u.display_name || u.username]));

  const inputSt = {
    width: '100%', height: 28, padding: '0 8px',
    background: 'var(--surface)', border: '1px solid var(--border-strong)',
    borderRadius: 'var(--r-sm)', fontSize: 12, color: 'var(--fg)',
    fontFamily: 'inherit', outline: 'none',
  };
  const bigInputSt = { ...inputSt, height: 34, fontSize: 14, fontWeight: 600 };

  function UserSelect({ label, field }) {
    const cur = d[field] ? String(d[field]) : '';
    return (
      <div>
        <div className="uppercase-label" style={{ marginBottom: 4 }}>{label}</div>
        <select value={cur} onChange={e => set(field, e.target.value ? parseInt(e.target.value) : null)}
          style={inputSt}>
          <option value="">— wybierz —</option>
          {users.map(u => (
            <option key={u.id} value={String(u.id)}>{u.display_name || u.username}</option>
          ))}
        </select>
      </div>
    );
  }

  return (
    <div style={{ padding: 24, maxWidth: 1100, margin: '0 auto', display: 'flex', flexDirection: 'column', gap: 16 }}>
      {/* Toolbar */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        <Button icon={<Ic.chevronLeft size={12} />} onClick={onBack}>Powrot</Button>
        <div style={{ flex: 1 }} />
        {msg && <span className="mono" style={{ fontSize: 11.5, color: msg.startsWith('Blad') ? 'var(--alarm)' : 'var(--ok)' }}>{msg}</span>}
        <Button variant="primary" icon={<Ic.check size={12} />} onClick={save} disabled={saving}>
          {saving ? 'Zapisuje...' : 'Zapisz'}
        </Button>
        <Button icon={<Ic.download size={12} />} onClick={openPdf}>PDF</Button>
      </div>

      {/* ── Naglowek dokumentu ── */}
      <Card>
        <div className="uppercase-label" style={{ marginBottom: 10 }}>Naglowek protokolu</div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <div>
            <div className="uppercase-label" style={{ marginBottom: 4 }}>Nr protokolu</div>
            <input value={d.nr_protokolu || ''} onChange={e => set('nr_protokolu', e.target.value)}
              placeholder="np. O26.021 /TPW /26" style={inputSt} />
          </div>
          <div>
            <div className="uppercase-label" style={{ marginBottom: 4 }}>Data osiowania</div>
            <input value={d.data_osiowania || ''} onChange={e => set('data_osiowania', e.target.value)}
              placeholder="2026-04-20" style={inputSt} />
          </div>
        </div>
      </Card>

      {/* ── Zleceniodawca ── */}
      <Card>
        <div className="uppercase-label" style={{ marginBottom: 10 }}>Zleceniodawca</div>
        <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 1fr 1fr', gap: 12 }}>
          <div>
            <div className="uppercase-label" style={{ marginBottom: 4 }}>Nazwa</div>
            <input value={d.zleceniodawca || ''} onChange={e => set('zleceniodawca', e.target.value)}
              placeholder="Nazwa firmy / zakladu" style={inputSt} />
          </div>
          <div>
            <div className="uppercase-label" style={{ marginBottom: 4 }}>Adres</div>
            <input value={d.adres || ''} onChange={e => set('adres', e.target.value)} style={inputSt} />
          </div>
          <div>
            <div className="uppercase-label" style={{ marginBottom: 4 }}>NIP</div>
            <input value={d.nip || ''} onChange={e => set('nip', e.target.value)} style={inputSt} />
          </div>
          <div>
            <div className="uppercase-label" style={{ marginBottom: 4 }}>Zlecenie nr / Z dnia</div>
            <div style={{ display: 'flex', gap: 6 }}>
              <input value={d.zlecenie_nr || ''} onChange={e => set('zlecenie_nr', e.target.value)}
                placeholder="nr" style={{ ...inputSt, width: 60 }} />
              <input value={d.data_zlecenia || ''} onChange={e => set('data_zlecenia', e.target.value)}
                placeholder="data" style={{ ...inputSt, flex: 1 }} />
            </div>
          </div>
        </div>
      </Card>

      {/* ── Urzadzenie ── */}
      <Card>
        <div className="uppercase-label" style={{ marginBottom: 10 }}>Urzadzenie</div>
        <div style={{ display: 'grid', gridTemplateColumns: '2fr 80px 100px 120px 140px 140px 100px', gap: 12 }}>
          <div>
            <div className="uppercase-label" style={{ marginBottom: 4 }}>Nazwa</div>
            <input value={d.machine_name || ''} onChange={e => set('machine_name', e.target.value)}
              placeholder="np. Pompa bagrowa nr 4" style={inputSt} />
          </div>
          <div>
            <div className="uppercase-label" style={{ marginBottom: 4 }}>Kod</div>
            <input value={d.machine_code || ''} onChange={e => set('machine_code', e.target.value)}
              placeholder="PB4" style={inputSt} />
          </div>
          <div>
            <div className="uppercase-label" style={{ marginBottom: 4 }}>Nr fab.</div>
            <input value={d.nr_fabryczny || ''} onChange={e => set('nr_fabryczny', e.target.value)} style={inputSt} />
          </div>
          <div>
            <div className="uppercase-label" style={{ marginBottom: 4 }}>Moc urz.</div>
            <input value={d.moc || ''} onChange={e => set('moc', e.target.value)} placeholder="90kW" style={inputSt} />
          </div>
          <div>
            <div className="uppercase-label" style={{ marginBottom: 4 }}>Typ</div>
            <input value={d.typ || ''} onChange={e => set('typ', e.target.value)} placeholder="pompa 1500 l/min" style={inputSt} />
          </div>
          <div>
            <div className="uppercase-label" style={{ marginBottom: 4 }}>Miejsce pracy</div>
            <input value={d.miejsce_pracy || ''} onChange={e => set('miejsce_pracy', e.target.value)} placeholder="EC Wroclaw" style={inputSt} />
          </div>
          <div>
            <div className="uppercase-label" style={{ marginBottom: 4 }}>obr/min</div>
            <input type="number" value={d.obr_min || ''} onChange={e => set('obr_min', e.target.value ? parseInt(e.target.value) : null)}
              placeholder="1500" style={inputSt} />
          </div>
        </div>
      </Card>

      {/* ── WARTOSCI POMIARU — 4 pola + kalkulacja ── */}
      <Card>
        <div className="uppercase-label" style={{ marginBottom: 10 }}>Wartosci pomiaru osiowania</div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr 1fr', gap: 16 }}>
          {[
            { key: 'v_pion', label: 'Przesuniecie na wysokosci', sym: 'V', note: 'mm' },
            { key: 'f1_rozwarcie', label: 'Rozwarcie gora-dol', sym: 'F1', note: 'mm  (↓ ujemna)' },
            { key: 'a_poziom', label: 'Przesuniecie na boki', sym: 'A', note: 'mm' },
            { key: 'f2_rozwarcie', label: 'Rozwarcie prawa-lewa', sym: 'F2', note: 'mm  (← ujemna)' },
          ].map(({ key, label, sym, note }) => (
            <div key={key} style={{
              background: 'var(--bg-sunken)', border: '1px solid var(--border)',
              borderRadius: 'var(--r-md)', padding: '14px 16px',
            }}>
              <div className="uppercase-label" style={{ marginBottom: 4 }}>{label}</div>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
                <span style={{ fontSize: 18, fontWeight: 700, color: 'var(--fg-muted)', minWidth: 28 }}>{sym} =</span>
                <input
                  type="number" step="0.001"
                  value={d[key] !== null && d[key] !== undefined ? d[key] : ''}
                  onChange={e => set(key, e.target.value === '' ? null : parseFloat(e.target.value))}
                  style={{ ...bigInputSt, width: 90, textAlign: 'center' }}
                />
                <span style={{ fontSize: 12, color: 'var(--fg-muted)' }}>{note}</span>
              </div>
            </div>
          ))}
        </div>

        {/* Kalkulacja live */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginTop: 16 }}>
          {[
            { label: 'Pozostawione przesuniecie maksymalne', val: przesun, formula: 'sqrt(V² + A²)' },
            { label: 'Pozostawione rozwarcie maksymalne', val: rozw, formula: 'sqrt(F1² + F2²)' },
          ].map(({ label, val, formula }) => (
            <div key={label} style={{
              background: val !== null ? 'var(--accent-weak)' : 'var(--bg-sunken)',
              border: `1px solid ${val !== null ? 'var(--accent-border)' : 'var(--border)'}`,
              borderRadius: 'var(--r-md)', padding: '14px 16px',
            }}>
              <div className="uppercase-label" style={{ marginBottom: 4 }}>{label}</div>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 10 }}>
                <span style={{
                  fontSize: 28, fontWeight: 700, letterSpacing: '-0.03em', fontFamily: 'var(--font-mono)',
                  color: val !== null ? 'var(--accent)' : 'var(--fg-subtle)',
                }}>
                  {val !== null ? fmtNum(val) : '–'}
                </span>
                <span style={{ fontSize: 12, color: 'var(--fg-muted)' }}>mm</span>
              </div>
              <div style={{ fontSize: 10, color: 'var(--fg-subtle)', marginTop: 4 }}>{formula}</div>
            </div>
          ))}
        </div>
      </Card>

      {/* ── TABELA TOLERANCJI ── */}
      <Card>
        <div className="uppercase-label" style={{ marginBottom: 10 }}>
          Zalecane tolerancje ustawienia walow
          {d.obr_min && <span style={{ marginLeft: 8, fontSize: 11, color: 'var(--accent)', fontWeight: 600 }}>
            (podswietlono dla {d.obr_min} obr/min)
          </span>}
        </div>
        <div style={{ overflowX: 'auto' }}>
          <table style={{ borderCollapse: 'collapse', width: '100%', fontSize: 12 }}>
            <thead>
              <tr style={{ background: 'var(--bg-sunken)' }}>
                <th rowSpan={2} style={thSt}>obr/min</th>
                <th colSpan={2} style={thSt}>Przesuniecie rownolegle [mm]</th>
                <th colSpan={2} style={thSt}>Rozwarcie katowe [mm]</th>
              </tr>
              <tr style={{ background: 'var(--bg-sunken)' }}>
                <th style={thSt}>Wystarczajaco</th>
                <th style={thSt}>Dobrze</th>
                <th style={thSt}>Wystarczajaco</th>
                <th style={thSt}>Dobrze</th>
              </tr>
            </thead>
            <tbody>
              {OSIOWANIE_NORMS.map((row, i) => (
                <tr key={row.rpm} style={{
                  background: i === hiRow ? 'rgba(34,197,94,0.12)' : 'transparent',
                  fontWeight: i === hiRow ? 600 : 400,
                }}>
                  <td style={tdSt} className="mono">{row.rpm}</td>
                  <td style={tdSt} className="mono">{row.pw.toFixed(2)}</td>
                  <td style={tdSt} className="mono">{row.pd.toFixed(2)}</td>
                  <td style={tdSt} className="mono">{row.rw.toFixed(2)}</td>
                  <td style={tdSt} className="mono">{row.rd.toFixed(2)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </Card>

      {/* ── Personel + Uwagi ── */}
      <Card>
        <div className="uppercase-label" style={{ marginBottom: 10 }}>Personel i uwagi</div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 2fr', gap: 12 }}>
          <UserSelect label="Osiowal" field="osilowal_user_id" />
          <UserSelect label="Zatwierdzil" field="zatwierdzil_user_id" />
          <div>
            <div className="uppercase-label" style={{ marginBottom: 4 }}>Uwagi</div>
            <input value={d.uwagi || ''} onChange={e => set('uwagi', e.target.value)}
              placeholder="np. osiowanie silnika" style={inputSt} />
          </div>
        </div>
      </Card>
    </div>
  );
}

const thSt = {
  border: '1px solid var(--border-strong)',
  padding: '6px 10px',
  textAlign: 'center',
  fontWeight: 600,
  fontSize: 11,
  color: 'var(--fg-muted)',
  textTransform: 'uppercase',
  letterSpacing: '0.04em',
};

const tdSt = {
  border: '1px solid var(--hairline)',
  padding: '5px 10px',
  textAlign: 'center',
};

Object.assign(window, { OsiowanieScreen });
