/* global React, Card, Button, Input, Ic, VS */
// Zakładka "Użytkownicy" — admin-only.
// Zarządzanie użytkownikami logującymi się do aplikacji (tabela {S}.users).
// Pola: login (username), Imię i nazwisko (display_name), email, rola, hasło.

function UsersScreen() {
  const role = VS.getRole();
  const isAdmin = role === 'admin';

  if (!isAdmin) {
    return (
      <div style={{ padding: 24, maxWidth: 800, margin: '0 auto' }}>
        <Card>
          <div className="uppercase-label" style={{ marginBottom: 8 }}>Użytkownicy</div>
          <div style={{ fontSize: 12.5, color: 'var(--fg-muted)' }}>
            Dostęp tylko dla administratora.
          </div>
        </Card>
      </div>
    );
  }

  const [list, setList] = React.useState(null);
  const [err, setErr] = React.useState('');
  const [msg, setMsg] = React.useState('');

  const [showAdd, setShowAdd] = React.useState(false);
  const [nLogin, setNLogin] = React.useState('');
  const [nName, setNName] = React.useState('');
  const [nEmail, setNEmail] = React.useState('');
  const [nPass, setNPass] = React.useState('');
  const [nRole, setNRole] = React.useState('pracownik');
  const [adding, setAdding] = React.useState(false);

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

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

  function flash(text) { setMsg(text); setTimeout(() => setMsg(''), 2200); }

  async function addUser() {
    if (!nLogin.trim() || !nPass.trim()) { flash('Login i hasło wymagane'); return; }
    setAdding(true);
    try {
      await VS.adminAddUser({
        username: nLogin.trim(),
        password: nPass,
        display_name: nName.trim(),
        email: nEmail.trim(),
        role: nRole,
      });
      setNLogin(''); setNName(''); setNEmail(''); setNPass(''); setNRole('pracownik');
      setShowAdd(false);
      load();
      flash('Dodano użytkownika.');
    } catch (e) {
      flash('Błąd: ' + e.message);
    } finally { setAdding(false); }
  }

  async function removeUser(u) {
    if (!confirm(`Usunąć użytkownika "${u.username}"?`)) return;
    try { await VS.adminDeleteUser(u.id); load(); flash('Usunięto.'); }
    catch (e) { flash('Błąd: ' + e.message); }
  }

  return (
    <div style={{ padding: 24, maxWidth: 1100, margin: '0 auto', display: 'flex', flexDirection: 'column', gap: 16 }}>
      <div>
        <div className="uppercase-label" style={{ marginBottom: 6 }}>Administracja</div>
        <h1 style={{ margin: 0, fontSize: 24, fontWeight: 500, letterSpacing: '-0.02em' }}>Użytkownicy</h1>
        <div style={{ fontSize: 12.5, color: 'var(--fg-muted)', marginTop: 6 }}>
          Lista osób logujących się do aplikacji. Imię i nazwisko pojawia się w dropdownach Operator / Zatwierdził.
        </div>
      </div>

      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        <span className="mono" style={{ fontSize: 11, color: 'var(--fg-muted)' }}>
          {list ? `${list.length} użytkowników` : ''}
        </span>
        <div style={{ flex: 1 }} />
        <Button variant="primary" icon={<Ic.plus size={12} />} onClick={() => setShowAdd(s => !s)}>
          {showAdd ? 'Ukryj' : 'Nowy użytkownik'}
        </Button>
      </div>

      {showAdd && (
        <Card>
          <div className="uppercase-label" style={{ marginBottom: 10 }}>Dodaj użytkownika</div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.2fr 1.2fr 1fr 130px', gap: 10 }}>
            <div>
              <div className="uppercase-label" style={{ marginBottom: 4 }}>Login</div>
              <Input value={nLogin} onChange={(e) => setNLogin(e.target.value)} placeholder="login" />
            </div>
            <div>
              <div className="uppercase-label" style={{ marginBottom: 4 }}>Imię i nazwisko</div>
              <Input value={nName} onChange={(e) => setNName(e.target.value)} placeholder="Jan Kowalski" />
            </div>
            <div>
              <div className="uppercase-label" style={{ marginBottom: 4 }}>E-mail</div>
              <Input value={nEmail} onChange={(e) => setNEmail(e.target.value)} placeholder="user@firma.pl" />
            </div>
            <div>
              <div className="uppercase-label" style={{ marginBottom: 4 }}>Hasło</div>
              <input type="password" value={nPass} onChange={(e) => setNPass(e.target.value)}
                style={inputStyle} />
            </div>
            <div>
              <div className="uppercase-label" style={{ marginBottom: 4 }}>Rola</div>
              <select value={nRole} onChange={(e) => setNRole(e.target.value)} style={inputStyle}>
                <option value="pracownik">pracownik</option>
                <option value="admin">admin</option>
              </select>
            </div>
          </div>
          <div style={{ marginTop: 12, display: 'flex', gap: 8, alignItems: 'center' }}>
            <Button variant="primary" icon={<Ic.check size={12} />} onClick={addUser} disabled={adding}>
              {adding ? 'Dodaję…' : 'Zapisz'}
            </Button>
            <Button onClick={() => setShowAdd(false)}>Anuluj</Button>
            {msg && <span className="mono" style={{ fontSize: 11.5, color: msg.startsWith('Błąd') ? 'var(--alarm)' : 'var(--ok)' }}>{msg}</span>}
          </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 użytkowników.
        </div></Card>
      )}
      {!err && list && list.length > 0 && (
        <Card pad={false}>
          <div style={{
            display: 'grid', gridTemplateColumns: '160px 1fr 1fr 110px 1fr',
            gap: 10, padding: '10px 16px', borderBottom: '1px solid var(--hairline)',
            fontSize: 10, color: 'var(--fg-muted)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600,
          }}>
            <div>Login</div>
            <div>Imię i nazwisko</div>
            <div>E-mail</div>
            <div>Rola</div>
            <div>Akcje</div>
          </div>
          {list.map((u, i) => (
            <UserRow key={u.id} user={u} last={i === list.length - 1} onChange={load} onRemove={() => removeUser(u)} />
          ))}
        </Card>
      )}

      {!showAdd && msg && (
        <span className="mono" style={{ fontSize: 11.5, color: msg.startsWith('Błąd') ? 'var(--alarm)' : 'var(--ok)' }}>{msg}</span>
      )}
    </div>
  );
}

function UserRow({ user, last, onChange, onRemove }) {
  const [editing, setEditing] = React.useState(false);
  const [name, setName] = React.useState(user.display_name || '');
  const [email, setEmail] = React.useState(user.email || '');
  const [role, setRole] = React.useState(user.role || 'pracownik');
  const [pass, setPass] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const [msg, setMsg] = React.useState('');

  React.useEffect(() => {
    setName(user.display_name || '');
    setEmail(user.email || '');
    setRole(user.role || 'pracownik');
    setPass('');
  }, [user.id, user.display_name, user.email, user.role]);

  async function save() {
    setBusy(true); setMsg('');
    try {
      const data = { display_name: name, email, role };
      if (pass.trim()) data.password = pass;
      await VS.adminUpdateUser(user.id, data);
      setEditing(false);
      setPass('');
      onChange && onChange();
    } catch (e) { setMsg('Błąd: ' + e.message); }
    finally { setBusy(false); }
  }

  if (!editing) {
    return (
      <div style={{
        display: 'grid', gridTemplateColumns: '160px 1fr 1fr 110px 1fr',
        gap: 10, padding: '10px 16px',
        borderBottom: last ? 'none' : '1px solid var(--hairline)',
        alignItems: 'center', fontSize: 12.5,
      }}>
        <div className="mono">{user.username}</div>
        <div>{user.display_name || <span style={{ color: 'var(--fg-subtle)' }}>—</span>}</div>
        <div style={{ color: 'var(--fg-muted)' }}>{user.email || <span style={{ color: 'var(--fg-subtle)' }}>—</span>}</div>
        <div>
          <span className="mono" style={{
            padding: '2px 6px', fontSize: 10.5,
            background: user.role === 'admin' ? 'var(--accent-weak)' : 'var(--bg-sunken)',
            color: user.role === 'admin' ? 'var(--accent)' : 'var(--fg-muted)',
            border: `1px solid ${user.role === 'admin' ? 'var(--accent-border)' : 'var(--border)'}`,
            borderRadius: 'var(--r-sm)', textTransform: 'uppercase', letterSpacing: '0.05em',
          }}>{user.role}</span>
        </div>
        <div style={{ display: 'flex', gap: 6 }}>
          <Button size="sm" icon={<Ic.pencil size={11} />} onClick={() => setEditing(true)}>Edytuj</Button>
          <Button size="sm" variant="danger" icon={<Ic.trash size={11} />} onClick={onRemove}>Usuń</Button>
        </div>
      </div>
    );
  }

  return (
    <div style={{
      display: 'grid', gridTemplateColumns: '160px 1fr 1fr 110px 1fr',
      gap: 10, padding: '10px 16px',
      borderBottom: last ? 'none' : '1px solid var(--hairline)',
      alignItems: 'center',
    }}>
      <div className="mono" style={{ color: 'var(--fg-muted)' }}>{user.username}</div>
      <Input value={name} onChange={(e) => setName(e.target.value)} placeholder="Imię i nazwisko" />
      <Input value={email} onChange={(e) => setEmail(e.target.value)} placeholder="email" />
      <select value={role} onChange={(e) => setRole(e.target.value)} style={inputStyle}>
        <option value="pracownik">pracownik</option>
        <option value="admin">admin</option>
      </select>
      <div style={{ display: 'flex', gap: 6, alignItems: 'center', flexWrap: 'wrap' }}>
        <input type="password" value={pass} onChange={(e) => setPass(e.target.value)}
          placeholder="nowe hasło" style={{ ...inputStyle, width: 110 }} />
        <Button size="sm" variant="primary" icon={<Ic.check size={11} />} onClick={save} disabled={busy}>
          {busy ? '…' : 'Zapisz'}
        </Button>
        <Button size="sm" icon={<Ic.x size={11} />} onClick={() => { setEditing(false); setPass(''); }}>Anuluj</Button>
        {msg && <span className="mono" style={{ fontSize: 10.5, color: 'var(--alarm)' }}>{msg}</span>}
      </div>
    </div>
  );
}

const inputStyle = {
  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',
};

Object.assign(window, { UsersScreen });
