/* global React, Card, Button, Input, Ic, VS */
// Zakładka "Maile" — admin-only.
// Lista odbiorców raportów (tabela vibrostore_contacts).
// Pojawiają się w pop-upie po kliknięciu "Wyślij raport mailem".

function MaileScreen() {
  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 }}>Maile</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 [nName, setNName] = React.useState('');
  const [nEmail, setNEmail] = React.useState('');
  const [nRole, setNRole] = React.useState('');
  const [adding, setAdding] = React.useState(false);

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

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

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

  async function add() {
    if (!nName.trim() || !nEmail.trim()) { flash('Nazwa i e-mail wymagane'); return; }
    setAdding(true);
    try {
      await VS.addContact({ name: nName.trim(), email: nEmail.trim(), role: nRole.trim() });
      setNName(''); setNEmail(''); setNRole('');
      setShowAdd(false);
      load();
      flash('Dodano odbiorcę.');
    } catch (e) { flash('Błąd: ' + e.message); }
    finally { setAdding(false); }
  }

  async function remove(c) {
    if (!confirm(`Usunąć "${c.name}"?`)) return;
    try { await VS.deleteContact(c.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' }}>Maile</h1>
        <div style={{ fontSize: 12.5, color: 'var(--fg-muted)', marginTop: 6 }}>
          Lista odbiorców raportów. Pojawia się w pop-upie po kliknięciu „Wyślij raport mailem".
        </div>
      </div>

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

      {showAdd && (
        <Card>
          <div className="uppercase-label" style={{ marginBottom: 10 }}>Dodaj odbiorcę</div>
          <div style={{ display: 'grid', gridTemplateColumns: '1.2fr 1.4fr 1fr', gap: 10 }}>
            <div>
              <div className="uppercase-label" style={{ marginBottom: 4 }}>Imię i nazwisko / Firma</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="email@firma.pl" />
            </div>
            <div>
              <div className="uppercase-label" style={{ marginBottom: 4 }}>Notatka / rola</div>
              <Input value={nRole} onChange={(e) => setNRole(e.target.value)} placeholder="np. utrzymanie ruchu" />
            </div>
          </div>
          <div style={{ marginTop: 12, display: 'flex', gap: 8, alignItems: 'center' }}>
            <Button variant="primary" icon={<Ic.check size={12} />} onClick={add} 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 odbiorców. Dodaj pierwszego, by mogli pojawić się w pop-upie wysyłki raportu.
        </div></Card>
      )}
      {!err && list && list.length > 0 && (
        <Card pad={false}>
          <div style={{
            display: 'grid', gridTemplateColumns: '1.2fr 1.4fr 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>Nazwa</div>
            <div>E-mail</div>
            <div>Notatka</div>
            <div>Akcje</div>
          </div>
          {list.map((c, i) => (
            <ContactRow key={c.id} item={c} last={i === list.length - 1} onChange={load} onRemove={() => remove(c)} />
          ))}
        </Card>
      )}

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

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

  React.useEffect(() => {
    setName(item.name || ''); setEmail(item.email || ''); setRole(item.role || '');
  }, [item.id, item.name, item.email, item.role]);

  async function save() {
    setBusy(true); setMsg('');
    try {
      await VS.updateContact(item.id, { name, email, role });
      setEditing(false);
      onChange && onChange();
    } catch (e) { setMsg('Błąd: ' + e.message); }
    finally { setBusy(false); }
  }

  if (!editing) {
    return (
      <div style={{
        display: 'grid', gridTemplateColumns: '1.2fr 1.4fr 1fr 200px',
        gap: 10, padding: '10px 16px',
        borderBottom: last ? 'none' : '1px solid var(--hairline)',
        alignItems: 'center', fontSize: 12.5,
      }}>
        <div>{item.name}</div>
        <div className="mono" style={{ color: 'var(--fg-muted)' }}>{item.email}</div>
        <div style={{ color: 'var(--fg-subtle)' }}>{item.role || '—'}</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: '1.2fr 1.4fr 1fr 200px',
      gap: 10, padding: '10px 16px',
      borderBottom: last ? 'none' : '1px solid var(--hairline)',
      alignItems: 'center',
    }}>
      <Input value={name} onChange={(e) => setName(e.target.value)} placeholder="Nazwa" />
      <Input value={email} onChange={(e) => setEmail(e.target.value)} placeholder="email" />
      <Input value={role} onChange={(e) => setRole(e.target.value)} placeholder="notatka" />
      <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
        <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)}>Anuluj</Button>
        {msg && <span className="mono" style={{ fontSize: 10.5, color: 'var(--alarm)' }}>{msg}</span>}
      </div>
    </div>
  );
}

Object.assign(window, { MaileScreen });
