/* ============================================================
   KODILA — Admin: Pravice
   ============================================================ */

const PERMISSION_MODULES = [
  { key: 'sifranti', label: 'Šifranti' },
  { key: 'dokumenti', label: 'Dokumenti' },
  { key: 'admin', label: 'Admin panel' },
  { key: 'aplikacije', label: 'Aplikacije' },
];

function emptyPermissionMap(value) {
  const map = {};
  PERMISSION_MODULES.forEach(m => { map[m.key] = value; });
  return map;
}

function permissionCheckboxCol(mod) {
  return {
    field: mod.key, headerName: mod.label, width: 130,
    cellRenderer: 'agCheckboxCellRenderer', cellEditor: 'agCheckboxCellEditor',
    editable: true, sortable: false, filter: false,
  };
}

const PRAVICE_COLS = [
  { field: 'id', headerName: 'ID', width: 70, cellClass: 'cell-mono', pinned: 'left' },
  { field: 'fullName', headerName: 'Ime in priimek', flex: 2, minWidth: 200, cellRenderer: userNameRenderer },
  { field: 'email', headerName: 'E-pošta', minWidth: 190 },
  { field: 'groupName', headerName: 'Skupina', minWidth: 150, valueFormatter: p => p.value || 'Brez skupine' },
  ...PERMISSION_MODULES.map(permissionCheckboxCol),
];

/* --- Pravice po uporabnikih --- */
function PraviceUporabniki() {
  const toast = useToast();
  const [rows, setRows] = useState([]);
  const [loading, setLoading] = useState(true);
  const [selected, setSelected] = useState([]);

  const load = async () => {
    setLoading(true);
    const { ok, data } = await api('/api/permissions');
    if (ok) {
      setRows(data.users.map(u => ({ ...u, ...u.permissions })));
    } else {
      toast('Pravic ni bilo mogoče naložiti.', 'alert');
    }
    setLoading(false);
  };

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

  const applyResult = (data) => {
    setRows(rs => rs.map(r => r.id === data.user.id
      ? { ...r, groupId: data.user.groupId, groupName: data.user.groupName, ...data.user.permissions }
      : r));
  };

  const persist = async (userId, permissions) => {
    const { ok, data } = await api(`/api/permissions/users/${userId}`, { method: 'PUT', body: JSON.stringify({ permissions }) });
    if (!ok) {
      toast('Napaka pri shranjevanju pravic.', 'alert');
      return;
    }
    applyResult(data);
  };

  const onCellValueChanged = (p) => {
    const field = p.colDef.field;
    if (!PERMISSION_MODULES.some(m => m.key === field)) return;
    const map = {};
    PERMISSION_MODULES.forEach(m => { map[m.key] = m.key === field ? !!p.newValue : !!p.data[m.key]; });
    persist(p.data.id, map);
  };

  const bulkApply = async (grant) => {
    if (!selected.length) return;
    const map = emptyPermissionMap(grant);
    for (const row of selected) {
      await persist(row.id, map);
    }
    toast(grant ? 'Vse pravice dodeljene' : 'Vse pravice ponastavljene', grant ? 'check' : 'x');
  };

  return (
    <div>
      {loading
        ? <div className="muted" style={{ padding: '24px 0' }}>Nalaganje …</div>
        : (
          <DataGrid
            columnDefs={PRAVICE_COLS}
            rowData={rows}
            getRowId={d => d.id}
            selectable
            exportName="kodila-pravice"
            exportTitle="Pravice uporabnikov"
            searchPlaceholder="Išči po imenu, e-pošti…"
            onCellValueChanged={onCellValueChanged}
            onSelectionChange={setSelected}
            actions={
              <>
                <button className="btn btn-sm" disabled={!selected.length} onClick={() => bulkApply(false)}>
                  <span dangerouslySetInnerHTML={{ __html: I('x', 15) }} /> Ponastavi vse pravice
                </button>
                <button className="btn btn-sm btn-primary" disabled={!selected.length} onClick={() => bulkApply(true)}>
                  <span dangerouslySetInnerHTML={{ __html: I('check', 15) }} /> Dodeli vse pravice
                </button>
              </>
            }
          />
        )}
    </div>
  );
}

/* --- Vnosni obrazec skupine (drawer) --- */
function GroupForm({ initial, onSave, onClose }) {
  const isEdit = !!(initial && initial.id);
  const [name, setName] = useState(initial && initial.id ? initial.name : '');
  const [perms, setPerms] = useState(initial && initial.permissions ? { ...initial.permissions } : emptyPermissionMap(false));
  const [errors, setErrors] = useState({});
  const [saving, setSaving] = useState(false);

  const togglePerm = (key) => setPerms(p => ({ ...p, [key]: !p[key] }));

  const save = async () => {
    setSaving(true);
    const ok = await onSave(isEdit ? initial.id : null, { name: name.trim(), permissions: perms }, isEdit, setErrors);
    setSaving(false);
    if (ok) onClose();
  };

  const fieldError = (field) => {
    const codes = errors[field];
    if (!codes || !codes.length) return null;
    if (codes.includes('taken')) return 'Skupina s tem imenom že obstaja.';
    if (codes.includes('required')) return 'Ime skupine je obvezno.';
    return codes.join(', ');
  };

  return (
    <div className="overlay" onMouseDown={(e) => { if (e.target.classList.contains('overlay')) onClose(); }}>
      <div className="drawer" onMouseDown={e => e.stopPropagation()}>
        <div className="drawer-head">
          <div className="app-ico" style={tintStyle('brand')} dangerouslySetInnerHTML={{ __html: I('lock', 20) }} />
          <div className="grow">
            <div className="drawer-title">{isEdit ? 'Uredi skupino' : 'Nova skupina'}</div>
            <div className="muted" style={{ fontSize: 12.5 }}>Uporabniška skupina in nabor pravic</div>
          </div>
          <button className="btn btn-icon btn-ghost" onClick={onClose} dangerouslySetInnerHTML={{ __html: I('x', 18) }} />
        </div>

        <div className="drawer-body">
          <div className="form-grid">
            <div className="form-sec-title"><span dangerouslySetInnerHTML={{ __html: I('tag', 14) }} /> Osnovni podatki</div>
            <div className="field col-2">
              <label>Ime skupine <span className="req">*</span></label>
              <input className="input" value={name} onChange={e => setName(e.target.value)}
                placeholder="npr. Prodaja"
                style={fieldError('name') ? { borderColor: 'var(--danger)' } : null} />
              {fieldError('name') && <span style={{ color: 'var(--danger)', fontSize: 12 }}>{fieldError('name')}</span>}
            </div>

            <div className="form-sec-title"><span dangerouslySetInnerHTML={{ __html: I('lock', 14) }} /> Pravice</div>
            {PERMISSION_MODULES.map(m => (
              <div className="field" key={m.key}>
                <label className="check">
                  <input type="checkbox" checked={!!perms[m.key]} onChange={() => togglePerm(m.key)} /> {m.label}
                </label>
              </div>
            ))}
          </div>
        </div>

        <div className="drawer-foot">
          <span className="muted grow" style={{ fontSize: 12.5 }}>
            <span className="req">*</span> obvezna polja
          </span>
          <button className="btn" onClick={onClose}>Prekliči</button>
          <button className="btn btn-primary" onClick={save} disabled={saving}>
            <span dangerouslySetInnerHTML={{ __html: I('save', 16) }} /> {isEdit ? 'Shrani' : 'Ustvari skupino'}
          </button>
        </div>
      </div>
    </div>
  );
}

/* --- Uporabniške skupine --- */
function PraviceSkupine() {
  const toast = useToast();
  const [groups, setGroups] = useState([]);
  const [loading, setLoading] = useState(true);
  const [editing, setEditing] = useState(null);

  const load = async () => {
    setLoading(true);
    const { ok, data } = await api('/api/groups');
    if (ok) setGroups(data.groups);
    else toast('Skupin ni bilo mogoče naložiti.', 'alert');
    setLoading(false);
  };

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

  const save = async (id, payload, isEdit, setErrors) => {
    const { ok, data } = isEdit
      ? await api(`/api/groups/${id}`, { method: 'PUT', body: JSON.stringify(payload) })
      : await api('/api/groups', { method: 'POST', body: JSON.stringify(payload) });

    if (!ok) {
      setErrors(data.errors || {});
      return false;
    }

    setGroups(gs => isEdit ? gs.map(g => g.id === data.group.id ? data.group : g) : [...gs, data.group]);
    toast(isEdit ? 'Skupina posodobljena' : 'Skupina ustvarjena: ' + data.group.name, 'check');
    return true;
  };

  const remove = async (group) => {
    if (!window.confirm(`Izbrišem skupino "${group.name}"? Uporabniki v tej skupini bodo prestavljeni na "Brez skupine".`)) return;
    const { ok, data } = await api(`/api/groups/${group.id}/delete`, { method: 'POST' });
    if (!ok) {
      toast(data.error === 'system_group_locked' ? 'Sistemske skupine ni mogoče izbrisati.' : 'Brisanje ni uspelo.', 'alert');
      return;
    }
    setGroups(gs => gs.filter(g => g.id !== group.id));
    toast('Skupina izbrisana', 'trash');
  };

  return (
    <div className="card card-pad">
      <div className="row" style={{ justifyContent: 'space-between', marginBottom: 16 }}>
        <div className="muted" style={{ fontSize: 12.5 }}>
          Predloge naborov pravic, ki jih lahko dodeliš uporabnikom v modulu Uporabniki.
        </div>
        <button className="btn btn-primary btn-sm" onClick={() => setEditing({})}>
          <span dangerouslySetInnerHTML={{ __html: I('plus', 15) }} /> Nova skupina
        </button>
      </div>

      {loading ? (
        <div className="muted" style={{ padding: '24px 0' }}>Nalaganje …</div>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {groups.map(g => (
            <div key={g.id} className="row" style={{ justifyContent: 'space-between', padding: '12px 14px', border: '1px solid var(--border)', borderRadius: 10 }}>
              <div>
                <div className="row" style={{ gap: 8, alignItems: 'center' }}>
                  <span className="cell-strong">{g.name}</span>
                  {g.isSystem && <span className="badge brand" style={{ height: 18, fontSize: 11 }}>
                    <span dangerouslySetInnerHTML={{ __html: I('lock', 11) }} /> sistemska
                  </span>}
                  <span className="muted" style={{ fontSize: 12 }}>{g.userCount} uporabnikov</span>
                </div>
                <div className="muted" style={{ fontSize: 12, marginTop: 4 }}>
                  {PERMISSION_MODULES.filter(m => g.permissions[m.key]).map(m => m.label).join(', ') || 'Brez pravic'}
                </div>
              </div>
              <div className="row" style={{ gap: 8 }}>
                <button className="btn btn-sm" disabled={g.isSystem} onClick={() => setEditing(g)}>
                  <span dangerouslySetInnerHTML={{ __html: I('edit', 15) }} /> Uredi
                </button>
                <button className="btn btn-sm" disabled={g.isSystem} onClick={() => remove(g)}>
                  <span dangerouslySetInnerHTML={{ __html: I('trash', 15) }} /> Izbriši
                </button>
              </div>
            </div>
          ))}
          {groups.length === 0 && <div className="muted" style={{ padding: '12px 0' }}>Ni ustvarjenih skupin.</div>}
        </div>
      )}

      {editing !== null && (
        <GroupForm initial={editing} onSave={save} onClose={() => setEditing(null)} />
      )}
    </div>
  );
}

const PRAVICE_TABS = [
  { id: 'uporabniki', label: 'Pravice po uporabnikih' },
  { id: 'skupine', label: 'Uporabniške skupine' },
];

function Pravice({ currentUser }) {
  const [tab, setTab] = useState(PRAVICE_TABS[0].id);
  return (
    <div>
      <div className="seg" style={{ marginBottom: 16 }}>
        {PRAVICE_TABS.map(t => (
          <button key={t.id} className={tab === t.id ? 'active' : ''} onClick={() => setTab(t.id)}>{t.label}</button>
        ))}
      </div>
      {tab === 'uporabniki' && <PraviceUporabniki />}
      {tab === 'skupine' && <PraviceSkupine />}
    </div>
  );
}
Object.assign(window, { Pravice });
