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

function MeasurementsScreen({ onOpenSession }) {
  const [sites, setSites] = React.useState(null);
  const [siteId, setSiteId] = React.useState(() => {
    const saved = localStorage.getItem('vs_selected_site');
    return saved ? parseInt(saved, 10) : null;
  });
  const [machines, setMachines] = React.useState(null);
  const [loadingMachines, setLoadingMachines] = React.useState(false);
  const [query, setQuery] = React.useState('');
  const [selectedMachine, setSelectedMachine] = React.useState(null);
  const [sessions, setSessions] = React.useState(null);
  const [loadingSessions, setLoadingSessions] = React.useState(false);
  const [err, setErr] = React.useState('');
  const [logoBust, setLogoBust] = React.useState(0);
  const fileInputRef = React.useRef(null);
  const role = VS.getRole();
  const isAdmin = role === 'admin';

  React.useEffect(() => {
    VS.sites().then(s => {
      setSites(s);
      const existing = siteId && s.find(x => x.id === siteId);
      if (!existing) {
        const firstNonEmpty = s.find(x => (x.measurements_count || 0) > 0);
        const fallback = firstNonEmpty || s[0];
        if (fallback) setSiteId(fallback.id);
      }
    }).catch(e => setErr(e.message));
  }, []);

  React.useEffect(() => {
    if (!siteId) return;
    localStorage.setItem('vs_selected_site', String(siteId));
    setMachines(null);
    setSelectedMachine(null);
    setSessions(null);
    setLoadingMachines(true);
    VS.siteMachines(siteId)
      .then(m => setMachines(m))
      .catch(e => setErr(e.message))
      .finally(() => setLoadingMachines(false));
  }, [siteId]);

  async function selectMachine(m) {
    setSelectedMachine(m);
    setSessions(null);
    setLoadingSessions(true);
    try {
      const s = await VS.sessions(m.id, 50);
      setSessions(s);
    } catch (e) { setErr(e.message); }
    finally { setLoadingSessions(false); }
  }

  async function uploadLogo(e) {
    const file = e.target.files && e.target.files[0];
    if (!file || !siteId) return;
    try {
      await VS.uploadSiteLogo(siteId, file);
      setLogoBust(x => x + 1);
    } catch (err) { setErr(err.message); }
    e.target.value = '';
  }

  async function removeLogo() {
    if (!siteId) return;
    try {
      await VS.deleteSiteLogo(siteId);
      setLogoBust(x => x + 1);
    } catch (err) { setErr(err.message); }
  }

  const site = sites && sites.find(s => s.id === siteId);
  const filteredMachines = machines
    ? machines.filter(m => !query
        || m.name.toLowerCase().includes(query.toLowerCase())
        || (m.hall || '').toLowerCase().includes(query.toLowerCase()))
    : [];

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

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: 'calc(100vh - 56px)', overflow: 'hidden' }}>
      <SiteHeader
        site={site}
        sites={sites}
        onChange={setSiteId}
        logoBust={logoBust}
        isAdmin={isAdmin}
        fileInputRef={fileInputRef}
        onUpload={uploadLogo}
        onRemove={removeLogo}
      />

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

      <div style={{ display: 'grid', gridTemplateColumns: '360px 1fr', flex: 1, overflow: 'hidden' }}>
        <aside style={{ borderRight: '1px solid var(--border)', background: 'var(--bg-elev)', display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
          <div style={{ padding: 14, borderBottom: '1px solid var(--border)' }}>
            <Input
              icon={<Ic.search size={13} />}
              placeholder="Szukaj maszyny…"
              value={query}
              onChange={(e) => setQuery(e.target.value)}
            />
            {machines && (
              <div style={{ fontSize: 10.5, color: 'var(--fg-subtle)', marginTop: 8, textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600 }}>
                {filteredMachines.length} / {machines.length} maszyn
              </div>
            )}
          </div>

          <div style={{ overflowY: 'auto', flex: 1 }}>
            {loadingMachines && <LoadingState />}
            {!loadingMachines && machines && machines.length === 0 && (
              <div style={{ padding: 32, textAlign: 'center', color: 'var(--fg-muted)', fontSize: 12.5 }}>
                <div className="uppercase-label" style={{ marginBottom: 6 }}>Brak maszyn</div>
                <div>W tym zakładzie nie ma jeszcze zarejestrowanych pomiarów.</div>
              </div>
            )}
            {!loadingMachines && filteredMachines.length > 0 && (
              <MachineList
                machines={filteredMachines}
                selectedId={selectedMachine && selectedMachine.id}
                onSelect={selectMachine}
              />
            )}
          </div>
        </aside>

        <main style={{ overflowY: 'auto' }}>
          {!selectedMachine && <EmptyPicker />}
          {selectedMachine && (
            <MachineDetail
              machine={selectedMachine}
              siteName={site ? site.name : ''}
              sessions={sessions}
              loading={loadingSessions}
              onOpenSession={onOpenSession}
              onRefresh={() => selectMachine(selectedMachine)}
            />
          )}
        </main>
      </div>
    </div>
  );
}

function SiteHeader({ site, sites, onChange, logoBust, isAdmin, fileInputRef, onUpload, onRemove }) {
  const [logoErr, setLogoErr] = React.useState(false);
  React.useEffect(() => { setLogoErr(false); }, [site && site.id, logoBust]);

  return (
    <div style={{
      position: 'relative',
      padding: '18px 24px',
      borderBottom: '1px solid var(--border)',
      display: 'flex', alignItems: 'center', gap: 20,
      background: 'linear-gradient(135deg, var(--surface) 0%, var(--bg-elev) 100%)',
    }}>
      <div style={{
        width: 64, height: 64, borderRadius: 'var(--r-md)',
        border: '1px solid var(--border)',
        background: 'linear-gradient(145deg, var(--bg-sunken), var(--surface))',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        overflow: 'hidden', position: 'relative',
        boxShadow: 'inset 0 1px 0 rgba(255,255,255,0.06), 0 1px 2px rgba(0,0,0,0.04)',
      }}>
        {site && !logoErr ? (
          <img
            src={VS.siteLogoUrl(site.id) + '&b=' + logoBust}
            alt=""
            onError={() => setLogoErr(true)}
            style={{ width: '100%', height: '100%', objectFit: 'contain', padding: 6 }}
          />
        ) : (
          <span className="uppercase-label" style={{ color: 'var(--fg-subtle)', fontSize: 11, letterSpacing: '0.08em' }}>
            {site ? site.name.slice(0, 3).toUpperCase() : '—'}
          </span>
        )}
      </div>

      <div style={{ flex: 1, minWidth: 0 }}>
        <div className="uppercase-label" style={{ marginBottom: 6 }}>Zakład</div>
        <GlassDropdown
          value={site ? site.id : null}
          onChange={onChange}
          options={(sites || []).map((s) => ({
            value: s.id,
            label: s.name,
            count: s.measurements_count || 0,
          }))}
          placeholder="Wybierz zakład…"
          searchPlaceholder="Szukaj zakładu…"
          emptyLabel="Brak zakładów."
          size="lg"
          minWidth={320}
          maxWidth={420}
        />
      </div>

      {isAdmin && site && (
        <div style={{ display: 'flex', gap: 6 }}>
          <input
            ref={fileInputRef}
            type="file"
            accept=".png,.jpg,.jpeg,.svg"
            onChange={onUpload}
            style={{ display: 'none' }}
          />
          <Button
            size="sm" variant="ghost"
            icon={<Ic.upload size={12} />}
            onClick={() => fileInputRef.current && fileInputRef.current.click()}
          >
            Logo
          </Button>
          {!logoErr && (
            <Button size="sm" variant="ghost" onClick={onRemove}>Usuń</Button>
          )}
        </div>
      )}
    </div>
  );
}

function MachineList({ machines, selectedId, onSelect }) {
  const groups = React.useMemo(() => {
    const m = new Map();
    for (const item of machines) {
      const key = item.hall || '—';
      if (!m.has(key)) m.set(key, []);
      m.get(key).push(item);
    }
    return Array.from(m.entries());
  }, [machines]);

  return (
    <div>
      {groups.map(([hall, items]) => (
        <div key={hall}>
          <div style={{
            padding: '10px 14px 6px', fontSize: 10,
            color: 'var(--fg-subtle)', textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 600,
            background: 'var(--bg-sunken)', borderBottom: '1px solid var(--hairline)',
          }}>
            {hall} · {items.length}
          </div>
          {items.map((m) => {
            const active = m.id === selectedId;
            const st = statusFromAlarm(m.max_alarm);
            return (
              <div
                key={m.id}
                onClick={() => onSelect(m)}
                style={{
                  display: 'flex', alignItems: 'center', gap: 10,
                  padding: '10px 14px',
                  cursor: 'pointer',
                  background: active ? 'var(--surface)' : 'transparent',
                  borderLeft: active ? '2px solid var(--fg)' : '2px solid transparent',
                  borderBottom: '1px solid var(--hairline)',
                }}
                onMouseEnter={(e) => { if (!active) e.currentTarget.style.background = 'var(--bg-sunken)'; }}
                onMouseLeave={(e) => { if (!active) e.currentTarget.style.background = 'transparent'; }}
              >
                <StatusGlyph status={st} size={8} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: active ? 500 : 400, color: 'var(--fg)' }}>
                    {m.name}
                  </div>
                  <div className="mono" style={{ fontSize: 10.5, color: 'var(--fg-subtle)', marginTop: 2 }}>
                    {m.sessions} {m.sessions === 1 ? 'sesja' : 'sesji'}
                    {m.last_dtg && <> · ostatnia: {m.last_dtg}</>}
                  </div>
                </div>
                <Ic.chevronRight size={12} />
              </div>
            );
          })}
        </div>
      ))}
    </div>
  );
}

function MachineDetail({ machine, siteName, sessions, loading, onOpenSession, onRefresh }) {
  return (
    <>
      <div style={{ padding: '18px 24px', borderBottom: '1px solid var(--border)' }}>
        <Breadcrumb items={[
          { label: 'Pomiary' },
          { label: siteName },
          ...(machine.hall ? [{ label: machine.hall }] : []),
          { label: machine.name },
        ]} />
        <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginTop: 14 }}>
          <div>
            <h1 style={{ margin: 0, fontSize: 22, fontWeight: 500, letterSpacing: '-0.02em' }}>{machine.name}</h1>
            <div style={{ display: 'flex', gap: 18, marginTop: 8, fontSize: 11.5, color: 'var(--fg-muted)' }}>
              <span><span className="mono" style={{ color: 'var(--fg-subtle)' }}>ID</span>&nbsp; <span className="mono">{machine.id}</span></span>
              {machine.hall && <span><span className="mono" style={{ color: 'var(--fg-subtle)' }}>hala</span>&nbsp; {machine.hall}</span>}
              <span><span className="mono" style={{ color: 'var(--fg-subtle)' }}>sesji</span>&nbsp; <span className="mono">{machine.sessions}</span></span>
            </div>
          </div>
          <Button icon={<Ic.refresh size={12} />} onClick={onRefresh}>Odśwież</Button>
        </div>
      </div>

      <div style={{ padding: 24 }}>
        {loading && <LoadingState />}
        {!loading && sessions && sessions.length === 0 && (
          <Card>
            <div style={{ textAlign: 'center', padding: '24px 16px', color: 'var(--fg-muted)' }}>
              <div className="uppercase-label" style={{ marginBottom: 6 }}>Brak sesji</div>
              <div style={{ fontSize: 13 }}>Ta maszyna nie ma jeszcze wgranych pomiarów.</div>
            </div>
          </Card>
        )}
        {!loading && sessions && sessions.length > 0 && (
          <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 }}>Sesje pomiarowe</h3>
                <span className="uppercase-label">{sessions.length} sesji</span>
              </div>
            </div>

            <div style={{
              display: 'grid', gridTemplateColumns: '72px 1fr 80px 150px 20px',
              columnGap: 20,
              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>Data · godzina</div>
              <div style={{ textAlign: 'right' }}>Punkty</div>
              <div>Urządzenie</div>
              <div></div>
            </div>

            {sessions.map((s, i) => {
              const st = statusFromAlarm(s.max_alarm);
              const d = s.session_date || '';
              const dateOnly = d.length >= 8
                ? `${d.slice(6,8)}.${d.slice(4,6)}.${d.slice(0,4)}`
                : (s.date_display || '').replace(/-/g, '.').split(',')[0].trim();
              const timeMatch = (s.time_start || '').match(/\d{1,2}:\d{2}/);
              const timeOnly = timeMatch ? timeMatch[0] : '';
              return (
                <div
                  key={i}
                  onClick={() => onOpenSession && onOpenSession({ machine_id: machine.id, machine_name: machine.name, session_date: s.session_date })}
                  style={{
                    display: 'grid', gridTemplateColumns: '72px 1fr 80px 150px 20px',
                    columnGap: 20,
                    padding: '12px 16px', borderBottom: i < sessions.length - 1 ? '1px solid var(--hairline)' : 'none',
                    alignItems: 'center', fontSize: 12.5, cursor: 'pointer',
                    transition: 'background 0.1s',
                  }}
                  onMouseEnter={(e) => e.currentTarget.style.background = 'var(--bg-sunken)'}
                  onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}
                >
                  <div style={{ display: 'flex', alignItems: 'center' }}>
                    <StatusBadge status={st} size="sm" />
                  </div>
                  <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, minWidth: 0 }}>
                    <span style={{ fontSize: 13, fontWeight: 500, color: 'var(--fg)' }}>{dateOnly}</span>
                    {timeOnly && (
                      <span className="mono" style={{ fontSize: 11.5, color: 'var(--fg-subtle)' }}>{timeOnly}</span>
                    )}
                  </div>
                  <div className="mono" style={{ color: 'var(--fg-muted)', textAlign: 'right' }}>{s.point_count || 0}</div>
                  <div className="mono" style={{ fontSize: 11, color: 'var(--fg-muted)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{s.device_id || '—'}</div>
                  <div style={{ color: 'var(--fg-subtle)', display: 'flex', justifyContent: 'flex-end' }}>
                    <Ic.chevronRight size={14} />
                  </div>
                </div>
              );
            })}
          </Card>
        )}
      </div>
    </>
  );
}

function EmptyPicker() {
  return (
    <div style={{ padding: 48, maxWidth: 520, margin: '80px auto 0', textAlign: 'center', color: 'var(--fg-muted)' }}>
      <div style={{
        width: 44, height: 44, margin: '0 auto 16px',
        border: '1px solid var(--border)', borderRadius: 'var(--r-md)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        <Ic.measure size={20} />
      </div>
      <div style={{ fontSize: 15, fontWeight: 500, color: 'var(--fg)', marginBottom: 4 }}>Wybierz maszynę</div>
      <div style={{ fontSize: 12.5 }}>Kliknij maszynę w liście po lewej żeby zobaczyć jej sesje pomiarowe.</div>
    </div>
  );
}

Object.assign(window, { MeasurementsScreen });
