/* global React, Card, StatusBadge, StatusGlyph, STATUS_META, Ic, Button, Input, Breadcrumb, TrendChart, VS, LoadingState, ErrorState, statusFromAlarm, SchemaPicker */

function SessionDetailScreen({ machineId, machineName, sessionDate, onBack }) {
  const [detail, setDetail] = React.useState(null);
  const [err, setErr] = React.useState('');
  const [activePoint, setActivePoint] = React.useState(null);
  const [trend, setTrend] = React.useState(null);
  const [trendBusy, setTrendBusy] = React.useState(false);
  const [notes, setNotes] = React.useState({});
  const [notesBusy, setNotesBusy] = React.useState(false);
  const [notesMsg, setNotesMsg] = React.useState('');
  const [selectedSchemaLibId, setSelectedSchemaLibId] = React.useState(null);
  const [selectedSchemaName, setSelectedSchemaName] = React.useState('');
  const [showPicker, setShowPicker] = React.useState(false);

  React.useEffect(() => {
    (async () => {
      try {
        const d = await VS.sessionDetail(machineId, sessionDate);
        setDetail(d);
        setNotes(d.notes || {});
        if (d.points && d.points.length > 0) {
          const first = d.points[0];
          setActivePoint(first);
          loadTrend(first.point_name);
        }
      } catch (e) { setErr(e.message); }
    })();
  }, [machineId, sessionDate]);

  async function loadTrend(pointName) {
    setTrend(null); setTrendBusy(true);
    try {
      const t = await VS.trend(machineId, pointName, 50);
      setTrend(t);
    } catch (e) { /* ignore — point może nie mieć historii */ }
    finally { setTrendBusy(false); }
  }

  async function saveNotes() {
    setNotesBusy(true); setNotesMsg('');
    try {
      await VS.saveNotes(machineId, sessionDate, notes);
      setNotesMsg('Zapisano.');
      setTimeout(() => setNotesMsg(''), 2500);
    } catch (e) { setNotesMsg('Błąd: ' + e.message); }
    finally { setNotesBusy(false); }
  }

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

  const points = detail.points || [];
  const worst = points.reduce((a, p) => Math.max(a, p.alarm_level || 0), 0);
  const sessionStatus = statusFromAlarm(worst);
  const dateStr = sessionDate ? `${sessionDate.slice(0,4)}-${sessionDate.slice(4,6)}-${sessionDate.slice(6,8)}` : '';
  const alarmPoint = points.find(p => (p.alarm_level || 0) >= 3);

  const thresholds = (activePoint && activePoint.unit === 'mm/s')
    ? { warn: 4.5, alarm: 7.1 }
    : (activePoint && activePoint.unit === 'g')
      ? { warn: 2.0, alarm: 3.5 }
      : { warn: null, alarm: null };

  return (
    <div style={{ overflow: 'auto', height: 'calc(100vh - 56px)' }}>
      <div style={{ padding: '18px 24px', borderBottom: '1px solid var(--border)' }}>
        <Breadcrumb items={[
          { label: 'Pomiary', onClick: onBack },
          { label: machineName || detail.machine_name },
          { label: dateStr },
        ]} />
        <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginTop: 14 }}>
          <div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <h1 style={{ margin: 0, fontSize: 22, fontWeight: 500, letterSpacing: '-0.02em' }}>
                Sesja <span className="mono">{dateStr}</span>
              </h1>
              <StatusBadge status={sessionStatus} />
            </div>
            <div style={{ display: 'flex', gap: 18, marginTop: 8, fontSize: 11.5, color: 'var(--fg-muted)' }}>
              <span><span style={{ color: 'var(--fg-subtle)' }}>Maszyna</span>&nbsp; {detail.machine_name}</span>
              <span><span style={{ color: 'var(--fg-subtle)' }}>Punkty</span>&nbsp; <span className="mono">{points.length}</span></span>
              <span><span style={{ color: 'var(--fg-subtle)' }}>Norma</span>&nbsp; ISO 10816-3</span>
            </div>
          </div>
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
            <Button icon={<Ic.download size={12} />}
              onClick={() => window.open(`/api/export-excel?machine_id=${machineId}&session_date=${sessionDate}`, '_blank')}>
              Excel
            </Button>
            <Button icon={<Ic.search size={12} />} onClick={() => setShowPicker(true)}>
              Schemat kinematyczny
            </Button>
            <Button variant="primary" icon={<Ic.file size={12} />}
              onClick={() => {
                const extra = selectedSchemaLibId ? `&schema_library_id=${selectedSchemaLibId}` : '';
                window.open(`/api/report?machine_id=${machineId}&session_date=${sessionDate}${extra}`, '_blank');
              }}>
              Raport PDF
            </Button>
          </div>
        </div>
        {selectedSchemaLibId && (
          <div style={{
            marginTop: 10, fontSize: 11.5, color: 'var(--fg-muted)',
            display: 'flex', alignItems: 'center', gap: 8,
          }}>
            <span className="uppercase-label">Schemat</span>
            <span style={{ color: 'var(--fg)' }}>{selectedSchemaName || `#${selectedSchemaLibId}`}</span>
            <button
              onClick={() => { setSelectedSchemaLibId(null); setSelectedSchemaName(''); }}
              style={{
                background: 'transparent', border: '1px solid var(--border)',
                color: 'var(--fg-muted)', cursor: 'pointer',
                padding: '2px 8px', fontSize: 11, borderRadius: 3,
              }}>wyczyść</button>
          </div>
        )}
      </div>
      {showPicker && (
        <SchemaPicker
          currentId={selectedSchemaLibId}
          onPick={(id, name) => { setSelectedSchemaLibId(id); setSelectedSchemaName(name || ''); }}
          onClose={() => setShowPicker(false)}
        />
      )}

      {alarmPoint && (
        <div style={{
          background: 'var(--alarm-weak)', borderBottom: '1px solid var(--alarm-border)',
          padding: '10px 24px', display: 'flex', alignItems: 'center', gap: 10,
        }}>
          <StatusGlyph status="alarm" size={10} />
          <span style={{ fontSize: 12.5, fontWeight: 500, color: 'var(--alarm)' }}>
            Alarm: {alarmPoint.point_name} · <span className="mono">{alarmPoint.overall_value?.toFixed(2)} {alarmPoint.unit}</span>
          </span>
        </div>
      )}

      <div style={{ padding: 24, display: 'flex', flexDirection: 'column', gap: 16 }}>
        {/* Notatki — na górze, żeby nie zjeżdżać */}
        <Card>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
            <div className="uppercase-label">Notatki diagnostyka</div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              {notesMsg && <span className="mono" style={{ fontSize: 11, color: notesMsg.startsWith('Błąd') ? 'var(--alarm)' : 'var(--ok)' }}>{notesMsg}</span>}
              <Button size="sm" variant="primary" disabled={notesBusy} onClick={saveNotes}>
                {notesBusy ? 'Zapisuję…' : 'Zapisz'}
              </Button>
            </div>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12 }}>
            <NoteField label="Uwagi" value={notes.uwagi || ''} onChange={v => setNotes({ ...notes, uwagi: v })} />
            <NoteField label="Ocena" value={notes.ocena || ''} onChange={v => setNotes({ ...notes, ocena: v })} />
            <NoteField label="Zalecenia" value={notes.zalecenia || ''} onChange={v => setNotes({ ...notes, zalecenia: v })} />
            <NoteField label="Cel pomiaru" value={notes.cel_pomiaru || ''} onChange={v => setNotes({ ...notes, cel_pomiaru: v })} single />
            <NoteField label="Operator" value={notes.operator || ''} onChange={v => setNotes({ ...notes, operator: v })} single />
            <NoteField label="Zatwierdził" value={notes.zatwierdzil || ''} onChange={v => setNotes({ ...notes, zatwierdzil: v })} single />
          </div>
        </Card>

        {/* Trend */}
        <Card pad={false}>
          <div style={{ padding: '14px 20px', borderBottom: '1px solid var(--hairline)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <div>
              <div style={{ fontSize: 13, fontWeight: 500 }}>
                Trend · {activePoint ? activePoint.point_name : 'wybierz punkt'}
              </div>
              <div style={{ fontSize: 11, color: 'var(--fg-muted)', marginTop: 2 }}>
                {trend ? `${trend.data.length} pomiarów · ` : ''}
                <span className="mono">{activePoint?.unit || ''}</span>
              </div>
            </div>
          </div>
          <div style={{ padding: '16px 20px 8px', minHeight: 280 }}>
            {trendBusy && <div style={{ padding: 40, textAlign: 'center', color: 'var(--fg-muted)', fontSize: 12 }}>Ładowanie trendu…</div>}
            {!trendBusy && trend && trend.data.length > 0 && (
              <TrendChart
                data={trend.data.map(d => ({ date: d.date, value: d.value }))}
                thresholds={thresholds}
                unit={trend.unit || activePoint?.unit || ''}
              />
            )}
            {!trendBusy && (!trend || trend.data.length === 0) && (
              <div style={{ padding: 40, textAlign: 'center', color: 'var(--fg-muted)', fontSize: 12 }}>
                Brak historii dla tego punktu.
              </div>
            )}
          </div>
        </Card>

        {/* Punkty */}
        <Card pad={false}>
          <div style={{ padding: '12px 16px', borderBottom: '1px solid var(--hairline)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              <h3 style={{ margin: 0, fontSize: 13.5, fontWeight: 500 }}>Punkty pomiarowe</h3>
              <span className="uppercase-label">{points.length} punktów</span>
            </div>
            <span className="mono" style={{ fontSize: 10, color: 'var(--fg-subtle)', textTransform: 'uppercase', letterSpacing: '0.08em' }}>
              kliknij wiersz aby zobaczyć trend
            </span>
          </div>

          <div style={{
            display: 'grid', gridTemplateColumns: '60px 80px 80px 1fr 120px 80px',
            padding: '10px 16px', borderBottom: '1px solid var(--hairline)',
            fontSize: 10, color: 'var(--fg-muted)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600,
          }}>
            <div>Status</div>
            <div>Czas</div>
            <div>Łożysko</div>
            <div>Punkt</div>
            <div style={{ textAlign: 'right' }}>Wartość</div>
            <div style={{ textAlign: 'right' }}>Jednostka</div>
          </div>

          {points.length === 0 && (
            <div style={{ padding: 24, textAlign: 'center', color: 'var(--fg-muted)', fontSize: 12 }}>Brak punktów w tej sesji.</div>
          )}
          {points.map((p, i) => {
            const st = statusFromAlarm(p.alarm_level);
            const active = activePoint && activePoint.point_name === p.point_name;
            return (
              <div key={i}
                onClick={() => { setActivePoint(p); loadTrend(p.point_name); }}
                style={{
                  display: 'grid', gridTemplateColumns: '60px 80px 80px 1fr 120px 80px',
                  padding: '10px 16px', borderBottom: i < points.length - 1 ? '1px solid var(--hairline)' : 'none',
                  alignItems: 'center', fontSize: 12.5, cursor: 'pointer',
                  background: active ? 'var(--bg-sunken)' : 'transparent',
                }}
                onMouseEnter={(e) => { if (!active) e.currentTarget.style.background = 'var(--bg-sunken)'; }}
                onMouseLeave={(e) => { if (!active) e.currentTarget.style.background = 'transparent'; }}
              >
                <StatusGlyph status={st} size={10} />
                <span className="mono" style={{ color: 'var(--fg-muted)' }}>{p.time || '—'}</span>
                <span className="mono" style={{ color: 'var(--fg-subtle)' }}>{p.bearing_number ? `Ł${p.bearing_number}` : '—'}</span>
                <span style={{ fontWeight: active ? 500 : 400 }}>{p.point_name}</span>
                <span className="mono num" style={{
                  textAlign: 'right', fontWeight: st !== 'ok' && st !== 'idle' ? 600 : 400,
                  color: st === 'alarm' ? 'var(--alarm)' : st === 'warn' ? 'var(--warn)' : 'var(--fg)',
                }}>
                  {p.overall_value != null ? p.overall_value.toFixed(3) : '—'}
                </span>
                <span className="mono" style={{ textAlign: 'right', color: 'var(--fg-muted)' }}>{p.unit || ''}</span>
              </div>
            );
          })}
        </Card>

      </div>
    </div>
  );
}

function NoteField({ label, value, onChange, single }) {
  return (
    <label>
      <div className="uppercase-label" style={{ marginBottom: 6 }}>{label}</div>
      {single ? (
        <input
          value={value}
          onChange={(e) => onChange(e.target.value)}
          style={{
            width: '100%', height: 30, padding: '0 10px',
            background: 'var(--surface)',
            border: '1px solid var(--border-strong)',
            borderRadius: 'var(--r-sm)',
            fontSize: 12, color: 'var(--fg)', outline: 'none',
          }}
        />
      ) : (
        <textarea
          value={value}
          onChange={(e) => onChange(e.target.value)}
          rows={4}
          style={{
            width: '100%', padding: 10,
            background: 'var(--surface)',
            border: '1px solid var(--border-strong)',
            borderRadius: 'var(--r-sm)',
            fontSize: 12, color: 'var(--fg)', outline: 'none',
            fontFamily: 'inherit', resize: 'vertical',
          }}
        />
      )}
    </label>
  );
}

Object.assign(window, { SessionDetailScreen });
