/* global React, Card, Button, Input, Ic, VS */

function ConfigScreen() {
  const role = VS.getRole();
  const username = VS.getUsername();
  const isAdmin = role === 'admin';
  const [tab, setTab] = React.useState('overview');

  const tabs = [
    { id: 'overview', label: 'Ogólne' },
    { id: 'schema-library', label: 'Biblioteka schematów' },
    { id: 'zalecenia-facilities', label: 'Zakłady zaleceń' },
  ];

  return (
    <div style={{ padding: 24, maxWidth: 1100, margin: '0 auto', display: 'flex', flexDirection: 'column', gap: 16 }}>
      <div>
        <div className="uppercase-label" style={{ marginBottom: 6 }}>Ustawienia</div>
        <h1 style={{ margin: 0, fontSize: 24, fontWeight: 500, letterSpacing: '-0.02em' }}>Konfiguracja</h1>
        <div style={{ fontSize: 12.5, color: 'var(--fg-muted)', marginTop: 6 }}>
          Profil zalogowanego użytkownika oraz parametry systemu.
        </div>
      </div>

      {/* Tabs */}
      <div style={{
        display: 'flex', gap: 2,
        borderBottom: '1px solid var(--border)',
      }}>
        {tabs.map((t) => (
          <TabBtn key={t.id} active={tab === t.id} onClick={() => setTab(t.id)}>{t.label}</TabBtn>
        ))}
      </div>

      {tab === 'overview' && <OverviewTab username={username} role={role} isAdmin={isAdmin} />}
      {tab === 'schema-library' && <SchemaLibraryAdmin isAdmin={isAdmin} />}
      {tab === 'zalecenia-facilities' && <ZaleceniaFacilitiesAdmin isAdmin={isAdmin} />}
    </div>
  );
}

function TabBtn({ active, onClick, children }) {
  return (
    <button
      onClick={onClick}
      style={{
        padding: '8px 14px', fontSize: 12.5,
        background: 'transparent',
        border: 'none',
        borderBottom: '2px solid ' + (active ? 'var(--fg)' : 'transparent'),
        color: active ? 'var(--fg)' : 'var(--fg-muted)',
        fontWeight: active ? 500 : 400,
        cursor: 'pointer',
        fontFamily: 'inherit',
        marginBottom: -1,
      }}
    >{children}</button>
  );
}

function OverviewTab({ username, role, isAdmin }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: 12 }}>
      <Card>
        <div className="uppercase-label" style={{ marginBottom: 10 }}>Konto</div>
        <KV label="Login" value={username || '—'} mono />
        <KV label="Rola" value={role || 'brak'} />
        <div style={{ marginTop: 12, paddingTop: 12, borderTop: '1px solid var(--hairline)' }}>
          <button onClick={() => { VS.clearAuth(); window.dispatchEvent(new Event('vs:logout')); }}
            style={{
              width: '100%', padding: '8px 12px', fontSize: 12.5, cursor: 'pointer',
              background: 'var(--bg-sunken)', border: '1px solid var(--border-strong)',
              borderRadius: 'var(--r-sm)', color: 'var(--fg)', fontFamily: 'inherit',
            }}>Wyloguj</button>
        </div>
      </Card>

      <Card>
        <div className="uppercase-label" style={{ marginBottom: 10 }}>Normy alarmowe</div>
        <KV label="VEL RMS · ostrzeżenie" value="4.5 mm/s" mono />
        <KV label="VEL RMS · alarm" value="7.1 mm/s" mono />
        <KV label="ACC RMS · ostrzeżenie" value="2.0 g" mono />
        <KV label="ACC RMS · alarm" value="3.5 g" mono />
        <div style={{ fontSize: 11, color: 'var(--fg-subtle)', marginTop: 10 }}>
          Zgodne z ISO&nbsp;10816-3, klasa II (maszyny &lt;&nbsp;15&nbsp;kW).
        </div>
      </Card>

      <Card>
        <div className="uppercase-label" style={{ marginBottom: 10 }}>Integracje</div>
        <KV label="Źródło" value="SKF @ptitude Observer" />
        <KV label="Sync" value="Aptitude agent · heartbeat 10 s" />
        <KV label="Raporty" value="PDF + XLSX" />
      </Card>

      {isAdmin && (
        <Card>
          <div className="uppercase-label" style={{ marginBottom: 10 }}>Administracja</div>
          <div style={{ fontSize: 12.5, color: 'var(--fg-muted)', lineHeight: 1.5 }}>
            Przełącz się na zakładkę „Biblioteka schematów” lub „Zakłady zaleceń”
            aby zarządzać zasobami używanymi w protokołach.
          </div>
        </Card>
      )}
    </div>
  );
}

// ============================================================
// SCHEMA LIBRARY ADMIN
// ============================================================
function SchemaLibraryAdmin({ isAdmin }) {
  const [list, setList] = React.useState(null);
  const [cats, setCats] = React.useState([]);
  const [err, setErr] = React.useState('');
  const [filterCat, setFilterCat] = React.useState('');
  const [msg, setMsg] = React.useState('');

  // Add form
  const [newFile, setNewFile] = React.useState(null);
  const [newName, setNewName] = React.useState('');
  const [newCat, setNewCat] = React.useState('');
  const [adding, setAdding] = React.useState(false);
  const fileRef = React.useRef(null);

  const load = React.useCallback(() => {
    VS.schemaLibrary()
      .then((r) => setList(r || []))
      .catch((e) => setErr(e.message));
    VS.schemaLibraryCategories()
      .then((r) => setCats(r || []))
      .catch(() => setCats([]));
  }, []);

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

  async function addSchema() {
    if (!newFile) { setMsg('Wybierz plik obrazka.'); return; }
    setAdding(true); setMsg('');
    try {
      await VS.addSchemaLibrary(newFile, newName.trim(), newCat.trim());
      setNewFile(null); setNewName(''); setNewCat('');
      if (fileRef.current) fileRef.current.value = '';
      load();
      setMsg('Dodano schemat.');
      setTimeout(() => setMsg(''), 2500);
    } catch (e) {
      setMsg('Błąd: ' + e.message);
    } finally {
      setAdding(false);
    }
  }

  async function removeItem(id) {
    if (!confirm('Usunąć ten schemat z biblioteki?')) return;
    try {
      await VS.deleteSchemaLibrary(id);
      load();
    } catch (e) {
      alert('Błąd: ' + e.message);
    }
  }

  if (!isAdmin) {
    return (
      <Card>
        <div className="uppercase-label" style={{ marginBottom: 8 }}>Biblioteka schematów</div>
        <div style={{ fontSize: 12.5, color: 'var(--fg-muted)' }}>
          Tylko administrator może zarządzać biblioteką.
        </div>
      </Card>
    );
  }

  const filtered = (list || []).filter((it) => !filterCat || (it.category || '') === filterCat);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
      {/* Add */}
      <Card>
        <div className="uppercase-label" style={{ marginBottom: 10 }}>Dodaj schemat</div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 180px auto', gap: 10, alignItems: 'end' }}>
          <div>
            <div className="uppercase-label" style={{ marginBottom: 4 }}>Plik (JPG/PNG)</div>
            <input
              ref={fileRef}
              type="file"
              accept="image/*"
              onChange={(e) => setNewFile(e.target.files && e.target.files[0])}
              style={{ fontSize: 12 }}
            />
          </div>
          <div>
            <div className="uppercase-label" style={{ marginBottom: 4 }}>Nazwa</div>
            <Input value={newName} onChange={(e) => setNewName(e.target.value)} placeholder="np. Przekładnia NGC-140" />
          </div>
          <div>
            <div className="uppercase-label" style={{ marginBottom: 4 }}>Kategoria</div>
            <Input value={newCat} onChange={(e) => setNewCat(e.target.value)} placeholder="np. Przekładnie" />
          </div>
          <Button variant="primary" icon={<Ic.plus size={12} />} onClick={addSchema} disabled={adding || !newFile}>
            {adding ? 'Dodaję…' : 'Dodaj'}
          </Button>
        </div>
        {msg && (
          <div className="mono" style={{
            marginTop: 10, fontSize: 11.5,
            color: msg.startsWith('Błąd') ? 'var(--alarm)' : 'var(--ok)',
          }}>{msg}</div>
        )}
      </Card>

      {/* Filter */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
        <span className="uppercase-label">Filtr kategorii</span>
        <select
          value={filterCat}
          onChange={(e) => setFilterCat(e.target.value)}
          style={{
            height: 28, padding: '0 8px',
            background: 'var(--surface)',
            border: '1px solid var(--border-strong)',
            borderRadius: 'var(--r-sm)',
            fontSize: 12, color: 'var(--fg)',
          }}
        >
          <option value="">Wszystkie</option>
          {cats.map((c) => (
            <option key={c.category} value={c.category}>
              {c.category || '— bez kategorii —'} ({c.count})
            </option>
          ))}
        </select>
        <span className="mono" style={{ fontSize: 11, color: 'var(--fg-subtle)' }}>
          {list ? `${filtered.length} / ${list.length}` : ''}
        </span>
      </div>

      {/* List */}
      {err && (
        <div style={{
          padding: 12, background: 'var(--alarm-weak)',
          border: '1px solid var(--alarm-border)', color: 'var(--alarm)',
          fontFamily: 'var(--font-mono)', fontSize: 12, borderRadius: 'var(--r-sm)',
        }}>{err}</div>
      )}
      {!err && !list && <div style={{ padding: 24, textAlign: 'center', color: 'var(--fg-muted)' }}>Ładowanie…</div>}
      {!err && list && filtered.length === 0 && (
        <Card>
          <div style={{ textAlign: 'center', padding: 20, color: 'var(--fg-muted)', fontSize: 13 }}>
            Brak schematów.
          </div>
        </Card>
      )}
      {!err && filtered.length > 0 && (
        <Card pad={false}>
          <div style={{
            display: 'grid', gridTemplateColumns: '72px 1fr 1fr 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>Podgląd</div>
            <div>Nazwa</div>
            <div>Kategoria</div>
            <div>Akcje</div>
          </div>
          {filtered.map((it, i) => (
            <SchemaLibraryRow
              key={it.id}
              item={it}
              last={i === filtered.length - 1}
              onChange={load}
              onRemove={() => removeItem(it.id)}
            />
          ))}
        </Card>
      )}
    </div>
  );
}

function SchemaLibraryRow({ item, last, onChange, onRemove }) {
  const [name, setName] = React.useState(item.name || '');
  const [category, setCategory] = React.useState(item.category || '');
  const [busy, setBusy] = React.useState(false);
  const [msg, setMsg] = React.useState('');

  React.useEffect(() => {
    setName(item.name || '');
    setCategory(item.category || '');
  }, [item.id, item.name, item.category]);

  const dirty = name !== (item.name || '') || category !== (item.category || '');

  async function save() {
    setBusy(true); setMsg('');
    try {
      await VS.updateSchemaLibrary(item.id, { name, category });
      setMsg('ok');
      setTimeout(() => setMsg(''), 1500);
      onChange && onChange();
    } catch (e) {
      setMsg('Błąd: ' + e.message);
    } finally {
      setBusy(false);
    }
  }

  return (
    <div style={{
      display: 'grid', gridTemplateColumns: '72px 1fr 1fr 180px',
      gap: 10, padding: '10px 16px',
      borderBottom: last ? 'none' : '1px solid var(--hairline)',
      alignItems: 'center',
    }}>
      <div style={{
        width: 60, height: 60,
        background: 'var(--bg-sunken)',
        border: '1px solid var(--hairline)',
        borderRadius: 'var(--r-sm)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        overflow: 'hidden',
      }}>
        <img
          src={VS.schemaLibraryImageUrl(item.id)}
          alt=""
          loading="lazy"
          style={{ maxWidth: '100%', maxHeight: '100%', objectFit: 'contain' }}
        />
      </div>
      <Input value={name} onChange={(e) => setName(e.target.value)} placeholder="Nazwa" />
      <Input value={category} onChange={(e) => setCategory(e.target.value)} placeholder="Kategoria" />
      <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
        <Button size="sm" variant={dirty ? 'primary' : 'default'} onClick={save} disabled={busy || !dirty}>
          {busy ? '…' : 'Zapisz'}
        </Button>
        <Button size="sm" variant="danger" onClick={onRemove}>Usuń</Button>
        {msg && (
          <span className="mono" style={{ fontSize: 10, color: msg.startsWith('Błąd') ? 'var(--alarm)' : 'var(--ok)' }}>
            {msg === 'ok' ? '✓' : msg}
          </span>
        )}
      </div>
    </div>
  );
}

// ============================================================
// ZALECENIA FACILITIES ADMIN
// ============================================================
function ZaleceniaFacilitiesAdmin({ isAdmin }) {
  const [list, setList] = React.useState(null);
  const [err, setErr] = React.useState('');
  const [newCode, setNewCode] = React.useState('');
  const [newName, setNewName] = React.useState('');
  const [adding, setAdding] = React.useState(false);
  const [msg, setMsg] = React.useState('');

  const load = React.useCallback(() => {
    VS.zaleceniaFacilities()
      .then((r) => setList(r || []))
      .catch((e) => setErr(e.message));
  }, []);

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

  async function add() {
    if (!newCode.trim() || !newName.trim()) {
      setMsg('Podaj kod i nazwę.');
      return;
    }
    setAdding(true); setMsg('');
    try {
      await VS.addZaleceniaFacility({ code: newCode.trim(), name: newName.trim() });
      setNewCode(''); setNewName('');
      load();
      setMsg('Dodano.');
      setTimeout(() => setMsg(''), 2000);
    } catch (e) {
      setMsg('Błąd: ' + e.message);
    } finally {
      setAdding(false);
    }
  }

  async function remove(id) {
    if (!confirm('Usunąć ten zakład?')) return;
    try {
      await VS.deleteZaleceniaFacility(id);
      load();
    } catch (e) {
      alert('Błąd: ' + e.message);
    }
  }

  if (!isAdmin) {
    return (
      <Card>
        <div className="uppercase-label" style={{ marginBottom: 8 }}>Zakłady zaleceń remontowych</div>
        <div style={{ fontSize: 12.5, color: 'var(--fg-muted)' }}>
          Tylko administrator może zarządzać zakładami.
        </div>
      </Card>
    );
  }

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
      <Card>
        <div className="uppercase-label" style={{ marginBottom: 10 }}>Dodaj zakład</div>
        <div style={{ display: 'grid', gridTemplateColumns: '160px 1fr auto', gap: 10, alignItems: 'end' }}>
          <div>
            <div className="uppercase-label" style={{ marginBottom: 4 }}>Kod</div>
            <Input value={newCode} onChange={(e) => setNewCode(e.target.value)} placeholder="np. BC-1" />
          </div>
          <div>
            <div className="uppercase-label" style={{ marginBottom: 4 }}>Nazwa</div>
            <Input value={newName} onChange={(e) => setNewName(e.target.value)} placeholder="Pełna nazwa zakładu" />
          </div>
          <Button variant="primary" icon={<Ic.plus size={12} />} onClick={add} disabled={adding}>
            {adding ? 'Dodaję…' : 'Dodaj'}
          </Button>
        </div>
        {msg && (
          <div className="mono" style={{
            marginTop: 10, fontSize: 11.5,
            color: msg.startsWith('Błąd') ? 'var(--alarm)' : 'var(--ok)',
          }}>{msg}</div>
        )}
      </Card>

      {err && (
        <div style={{
          padding: 12, background: 'var(--alarm-weak)',
          border: '1px solid var(--alarm-border)', color: 'var(--alarm)',
          fontFamily: 'var(--font-mono)', fontSize: 12, borderRadius: 'var(--r-sm)',
        }}>{err}</div>
      )}
      {!err && !list && <div style={{ padding: 24, textAlign: 'center', color: 'var(--fg-muted)' }}>Ładowanie…</div>}
      {!err && list && list.length === 0 && (
        <Card>
          <div style={{ textAlign: 'center', padding: 20, color: 'var(--fg-muted)', fontSize: 13 }}>
            Brak zakładów.
          </div>
        </Card>
      )}
      {!err && list && list.length > 0 && (
        <Card pad={false}>
          <div style={{
            display: 'grid', gridTemplateColumns: '160px 1fr 200px',
            gap: 10, padding: '10px 16px', borderBottom: '1px solid var(--hairline)',
            fontSize: 10, color: 'var(--fg-muted)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600,
          }}>
            <div>Kod</div>
            <div>Nazwa</div>
            <div>Akcje</div>
          </div>
          {list.map((f, i) => (
            <FacilityRow
              key={f.id}
              item={f}
              last={i === list.length - 1}
              onChange={load}
              onRemove={() => remove(f.id)}
            />
          ))}
        </Card>
      )}
    </div>
  );
}

function FacilityRow({ item, last, onChange, onRemove }) {
  const [code, setCode] = React.useState(item.code || '');
  const [name, setName] = React.useState(item.name || '');
  const [busy, setBusy] = React.useState(false);
  const [msg, setMsg] = React.useState('');

  React.useEffect(() => {
    setCode(item.code || '');
    setName(item.name || '');
  }, [item.id, item.code, item.name]);

  const dirty = code !== (item.code || '') || name !== (item.name || '');

  async function save() {
    setBusy(true); setMsg('');
    try {
      await VS.updateZaleceniaFacility(item.id, { code, name });
      setMsg('ok');
      setTimeout(() => setMsg(''), 1500);
      onChange && onChange();
    } catch (e) {
      setMsg('Błąd: ' + e.message);
    } finally {
      setBusy(false);
    }
  }

  return (
    <div style={{
      display: 'grid', gridTemplateColumns: '160px 1fr 200px',
      gap: 10, padding: '10px 16px',
      borderBottom: last ? 'none' : '1px solid var(--hairline)',
      alignItems: 'center',
    }}>
      <Input value={code} onChange={(e) => setCode(e.target.value)} placeholder="Kod" />
      <Input value={name} onChange={(e) => setName(e.target.value)} placeholder="Nazwa" />
      <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
        <Button size="sm" variant={dirty ? 'primary' : 'default'} onClick={save} disabled={busy || !dirty}>
          {busy ? '…' : 'Zapisz'}
        </Button>
        <Button size="sm" variant="danger" onClick={onRemove}>Usuń</Button>
        {msg && (
          <span className="mono" style={{ fontSize: 10, color: msg.startsWith('Błąd') ? 'var(--alarm)' : 'var(--ok)' }}>
            {msg === 'ok' ? '✓' : msg}
          </span>
        )}
      </div>
    </div>
  );
}

function KV({ label, value, mono }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', padding: '4px 0', fontSize: 12.5 }}>
      <span style={{ color: 'var(--fg-muted)' }}>{label}</span>
      <span className={mono ? 'mono' : ''} style={{ color: 'var(--fg)', fontWeight: 500 }}>{value}</span>
    </div>
  );
}

Object.assign(window, { ConfigScreen });
