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

function MyStampScreen() {
  const [stamp, setStamp] = React.useState(null);
  const [err, setErr] = React.useState('');
  const [msg, setMsg] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const [imgBust, setImgBust] = React.useState(0);
  const fileInputRef = React.useRef(null);

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

  // admin: wszystkie pieczątki
  const [allStamps, setAllStamps] = React.useState(null);
  const [allStampsErr, setAllStampsErr] = React.useState('');
  const [allBust, setAllBust] = React.useState({});

  React.useEffect(() => {
    VS.myStamp()
      .then((s) => setStamp(s))
      .catch((e) => setErr(e.message));
  }, []);

  React.useEffect(() => {
    if (!isAdmin) return;
    VS.userStamps()
      .then((list) => setAllStamps(list))
      .catch((e) => setAllStampsErr(e.message));
  }, [isAdmin]);

  function setField(k, v) {
    setStamp((s) => ({ ...s, [k]: v }));
  }

  async function save() {
    if (!stamp) return;
    setBusy(true); setMsg('');
    try {
      await VS.saveMyStamp({ name: stamp.name || '', cert_number: stamp.cert_number || '' });
      setMsg('Zapisano.');
      setTimeout(() => setMsg(''), 2500);
    } catch (e) {
      setMsg('Błąd: ' + e.message);
    } finally {
      setBusy(false);
    }
  }

  async function uploadImage(e) {
    const file = e.target.files && e.target.files[0];
    if (!file) return;
    setBusy(true); setMsg('');
    try {
      await VS.uploadMyStampImage(file);
      setStamp((s) => ({ ...s, has_image: true }));
      setImgBust((x) => x + 1);
      setMsg('Obrazek wgrany.');
      setTimeout(() => setMsg(''), 2500);
    } catch (err) {
      setMsg('Błąd: ' + err.message);
    } finally {
      setBusy(false);
      e.target.value = '';
    }
  }

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

  return (
    <div style={{ padding: 24, maxWidth: 960, margin: '0 auto', display: 'flex', flexDirection: 'column', gap: 16 }}>
      <div>
        <div className="uppercase-label" style={{ marginBottom: 6 }}>Pieczątka</div>
        <h1 style={{ margin: 0, fontSize: 24, fontWeight: 500, letterSpacing: '-0.02em' }}>Moja pieczątka</h1>
        <div style={{ fontSize: 12.5, color: 'var(--fg-muted)', marginTop: 6 }}>
          Dane pieczątki wykorzystywane w protokołach i raportach.
        </div>
      </div>

      <Card>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14 }}>
          <div className="uppercase-label">Moja pieczątka</div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            {msg && (
              <span className="mono" style={{ fontSize: 11, color: msg.startsWith('Błąd') ? 'var(--alarm)' : 'var(--ok)' }}>
                {msg}
              </span>
            )}
            <Button size="sm" variant="primary" onClick={save} disabled={busy}>
              {busy ? 'Zapisuję…' : 'Zapisz'}
            </Button>
          </div>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 12, marginBottom: 16 }}>
          <StampField
            label="Imię i nazwisko"
            value={stamp.name || ''}
            onChange={(v) => setField('name', v)}
          />
          <StampField
            label="Nr świadectwa kwalifikacyjnego"
            value={stamp.cert_number || ''}
            onChange={(v) => setField('cert_number', v)}
          />
        </div>

        <div style={{ paddingTop: 14, borderTop: '1px solid var(--hairline)' }}>
          <div className="uppercase-label" style={{ marginBottom: 10 }}>Obrazek pieczątki</div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
            <div style={{
              width: 200, height: 80,
              border: '1px solid var(--border)',
              borderRadius: 'var(--r-sm)',
              background: 'var(--bg-sunken)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              overflow: 'hidden',
            }}>
              {stamp.has_image ? (
                <img
                  src={VS.userStampImageUrl(stamp.user_id, imgBust)}
                  alt="pieczątka"
                  style={{ maxWidth: '100%', maxHeight: '100%', objectFit: 'contain' }}
                />
              ) : (
                <span className="uppercase-label" style={{ color: 'var(--fg-subtle)' }}>brak</span>
              )}
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              <input
                ref={fileInputRef}
                type="file"
                accept="image/png,image/jpeg"
                onChange={uploadImage}
                style={{ display: 'none' }}
              />
              <Button
                size="sm" variant="default"
                icon={<Ic.upload size={12} />}
                onClick={() => fileInputRef.current && fileInputRef.current.click()}
                disabled={busy}
              >
                {stamp.has_image ? 'Zmień obrazek' : 'Wgraj obrazek'}
              </Button>
              <div style={{ fontSize: 11, color: 'var(--fg-subtle)' }}>
                PNG lub JPEG, rekomendowane 400×160 px.
              </div>
            </div>
          </div>
        </div>
      </Card>

      {isAdmin && (
        <AdminStampsSection
          stamps={allStamps}
          setStamps={setAllStamps}
          err={allStampsErr}
          allBust={allBust}
          setAllBust={setAllBust}
        />
      )}
    </div>
  );
}

function StampField({ label, value, onChange }) {
  return (
    <label>
      <div className="uppercase-label" style={{ marginBottom: 6 }}>{label}</div>
      <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',
          fontFamily: 'inherit',
        }}
      />
    </label>
  );
}

function AdminStampsSection({ stamps, setStamps, err, allBust, setAllBust }) {
  const [open, setOpen] = React.useState(true);
  return (
    <Card>
      <div
        onClick={() => setOpen((o) => !o)}
        style={{
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          cursor: 'pointer', userSelect: 'none',
        }}
      >
        <div>
          <div className="uppercase-label">Administracja</div>
          <div style={{ fontSize: 14, fontWeight: 500, marginTop: 2 }}>Pieczątki wszystkich użytkowników</div>
        </div>
        <div style={{ color: 'var(--fg-muted)', transform: open ? 'rotate(180deg)' : 'rotate(0)', transition: 'transform 0.15s' }}>
          <Ic.chevronDown size={16} />
        </div>
      </div>

      {open && (
        <div style={{ marginTop: 14 }}>
          {err && (
            <div style={{
              padding: '8px 12px', marginBottom: 10,
              background: 'var(--alarm-weak)', border: '1px solid var(--alarm-border)',
              borderRadius: 'var(--r-sm)', color: 'var(--alarm)', fontSize: 12,
            }}>{err}</div>
          )}
          {!stamps && !err && <div style={{ padding: 20, color: 'var(--fg-muted)', fontSize: 12 }}>Ładowanie…</div>}
          {stamps && stamps.length === 0 && (
            <div style={{ padding: 20, color: 'var(--fg-muted)', fontSize: 12 }}>Brak użytkowników.</div>
          )}
          {stamps && stamps.length > 0 && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              <div style={{
                display: 'grid',
                gridTemplateColumns: '180px 1fr 180px 120px 220px',
                gap: 10,
                padding: '6px 8px',
                fontSize: 10, color: 'var(--fg-muted)',
                textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600,
                borderBottom: '1px solid var(--hairline)',
              }}>
                <div>Użytkownik</div>
                <div>Imię i nazwisko</div>
                <div>Nr świadectwa</div>
                <div>Pieczątka</div>
                <div>Akcje</div>
              </div>
              {stamps.map((row) => (
                <AdminStampRow
                  key={row.user_id}
                  row={row}
                  bust={allBust[row.user_id] || 0}
                  onChange={(patch) => {
                    setStamps((list) =>
                      list.map((s) => (s.user_id === row.user_id ? { ...s, ...patch } : s)));
                  }}
                  bumpBust={() =>
                    setAllBust((b) => ({ ...b, [row.user_id]: (b[row.user_id] || 0) + 1 }))
                  }
                />
              ))}
            </div>
          )}
        </div>
      )}
    </Card>
  );
}

function AdminStampRow({ row, onChange, bust, bumpBust }) {
  const [busy, setBusy] = React.useState(false);
  const [msg, setMsg] = React.useState('');
  const fileRef = React.useRef(null);

  async function save() {
    setBusy(true); setMsg('');
    try {
      await VS.saveUserStamp(row.user_id, { name: row.name || '', cert_number: row.cert_number || '' });
      setMsg('OK');
      setTimeout(() => setMsg(''), 2000);
    } catch (e) {
      setMsg('Błąd');
    } finally {
      setBusy(false);
    }
  }

  async function upload(e) {
    const file = e.target.files && e.target.files[0];
    if (!file) return;
    setBusy(true); setMsg('');
    try {
      await VS.uploadUserStampImage(row.user_id, file);
      onChange({ has_image: true });
      bumpBust();
      setMsg('OK');
      setTimeout(() => setMsg(''), 2000);
    } catch (err) {
      setMsg('Błąd');
    } finally {
      setBusy(false);
      e.target.value = '';
    }
  }

  return (
    <div style={{
      display: 'grid',
      gridTemplateColumns: '180px 1fr 180px 120px 220px',
      gap: 10,
      padding: '8px',
      alignItems: 'center',
      borderBottom: '1px solid var(--hairline)',
    }}>
      <div style={{ minWidth: 0 }}>
        <div style={{ fontSize: 12.5, fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
          {row.username}
        </div>
        <div className="mono" style={{ fontSize: 10.5, color: 'var(--fg-muted)' }}>
          {row.role || 'user'}
        </div>
      </div>

      <input
        value={row.name || ''}
        onChange={(e) => onChange({ name: e.target.value })}
        placeholder="Imię i nazwisko"
        style={{
          width: '100%', height: 28, padding: '0 10px',
          background: 'var(--surface)',
          border: '1px solid var(--border-strong)',
          borderRadius: 'var(--r-sm)',
          fontSize: 12, color: 'var(--fg)', outline: 'none',
          fontFamily: 'inherit',
        }}
      />

      <input
        value={row.cert_number || ''}
        onChange={(e) => onChange({ cert_number: e.target.value })}
        placeholder="nr świadectwa"
        style={{
          width: '100%', height: 28, padding: '0 10px',
          background: 'var(--surface)',
          border: '1px solid var(--border-strong)',
          borderRadius: 'var(--r-sm)',
          fontSize: 12, color: 'var(--fg)', outline: 'none',
          fontFamily: 'inherit',
        }}
      />

      <div style={{
        width: 112, height: 44,
        border: '1px solid var(--border)',
        borderRadius: 'var(--r-sm)',
        background: 'var(--bg-sunken)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        overflow: 'hidden',
      }}>
        {row.has_image ? (
          <img
            src={VS.userStampImageUrl(row.user_id, bust)}
            alt=""
            style={{ maxWidth: '100%', maxHeight: '100%', objectFit: 'contain' }}
          />
        ) : (
          <span className="uppercase-label" style={{ color: 'var(--fg-subtle)', fontSize: 9 }}>brak</span>
        )}
      </div>

      <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
        <input
          ref={fileRef}
          type="file"
          accept="image/png,image/jpeg"
          onChange={upload}
          style={{ display: 'none' }}
        />
        <Button size="sm" variant="ghost"
          icon={<Ic.upload size={11} />}
          disabled={busy}
          onClick={() => fileRef.current && fileRef.current.click()}>
          Upload
        </Button>
        <Button size="sm" variant="primary" onClick={save} disabled={busy}>
          Zapisz
        </Button>
        {msg && (
          <span className="mono" style={{ fontSize: 10, color: msg === 'OK' ? 'var(--ok)' : 'var(--alarm)' }}>
            {msg}
          </span>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { MyStampScreen });
