/* ============================================================
   KODILA — Šifrant: Države
   ============================================================ */

const COUNTRY_STATUS_LABEL = { active: 'Aktivna', inactive: 'Nedejavna' };

function countryStatusRenderer(p) {
  const label = COUNTRY_STATUS_LABEL[p.value] || p.value;
  const cls = (window.STATUS_MAP[label] || 'default');
  const c = cls === 'default' ? '' : cls;
  return `<span class="badge ${c}"><span class="dot"></span>${label}</span>`;
}

function countryEuRenderer(p) {
  return p.value
    ? `<span class="badge info"><span class="dot"></span>Da</span>`
    : `<span class="muted">Ne</span>`;
}

const COUNTRY_COLS = [
  { field: 'id', headerName: 'ID', width: 70, cellClass: 'cell-mono', pinned: 'left' },
  { field: 'code', headerName: 'Oznaka', width: 100, cellClass: 'cell-mono cell-strong' },
  { field: 'name', headerName: 'Ime', flex: 2, minWidth: 200 },
  {
    field: 'currencyCode', headerName: 'Valuta', width: 160,
    valueFormatter: p => p.data.currencyCode ? `${p.data.currencyCode} — ${p.data.currencyName}` : '—',
  },
  { field: 'isEu', headerName: 'Članica EU', width: 130, cellRenderer: countryEuRenderer },
  { field: 'status', headerName: 'Status', width: 130, cellRenderer: countryStatusRenderer },
];

const EMPTY_COUNTRY = { id: null, code: '', name: '', currencyId: '', isEu: false, status: 'active' };

const COUNTRY_ERROR_MESSAGES = {
  code: {
    required: 'Oznaka države je obvezna.',
    invalid: 'Oznaka mora biti sestavljena iz 2 črk (ISO 3166-1, npr. SI).',
    taken: 'Ta oznaka države že obstaja.',
  },
  name: { required: 'Ime države je obvezno.' },
  currencyId: { invalid: 'Izbrana valuta ne obstaja.' },
};

function DrzavaForm({ initial, currencies, onSave, onClose }) {
  const isEdit = !!(initial && initial.id);
  const [f, setF] = useState(initial && initial.id
    ? { ...EMPTY_COUNTRY, ...initial, currencyId: initial.currencyId != null ? String(initial.currencyId) : '' }
    : { ...EMPTY_COUNTRY });
  const [errors, setErrors] = useState({});
  const [saving, setSaving] = useState(false);
  const set = (k, v) => setF(s => ({ ...s, [k]: v }));

  const save = async () => {
    setSaving(true);
    const payload = {
      code: f.code.trim().toUpperCase(),
      name: f.name.trim(),
      currencyId: f.currencyId === '' ? null : Number(f.currencyId),
      isEu: !!f.isEu,
      status: f.status,
    };
    const ok = await onSave(f.id, payload, isEdit, setErrors);
    setSaving(false);
    if (ok) onClose();
  };

  const fieldError = (field) => {
    const codes = errors[field];
    if (!codes || !codes.length) return null;
    const map = COUNTRY_ERROR_MESSAGES[field] || {};
    return codes.map(c => map[c] || c).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('info')} dangerouslySetInnerHTML={{ __html: I('globe', 20) }} />
          <div className="grow">
            <div className="drawer-title">{isEdit ? 'Uredi državo' : 'Nova država'}</div>
            <div className="muted" style={{ fontSize: 12.5 }}>{isEdit ? f.name : 'Šifrant držav'}</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">
              <label>Oznaka (ISO 3166-1) <span className="req">*</span></label>
              <input className="input mono" value={f.code} maxLength={2}
                onChange={e => set('code', e.target.value.toUpperCase())}
                placeholder="SI"
                style={fieldError('code') ? { borderColor: 'var(--danger)' } : null} />
              {fieldError('code') && <span style={{ color: 'var(--danger)', fontSize: 12 }}>{fieldError('code')}</span>}
            </div>
            <div className="field">
              <label>Valuta</label>
              <select className="select" value={f.currencyId} onChange={e => set('currencyId', e.target.value)}
                style={fieldError('currencyId') ? { borderColor: 'var(--danger)' } : null}>
                <option value="">— brez —</option>
                {currencies.map(c => <option key={c.id} value={c.id}>{c.code} — {c.name}</option>)}
              </select>
              {fieldError('currencyId') && <span style={{ color: 'var(--danger)', fontSize: 12 }}>{fieldError('currencyId')}</span>}
            </div>

            <div className="field col-2">
              <label>Ime <span className="req">*</span></label>
              <input className="input" value={f.name} onChange={e => set('name', e.target.value)}
                placeholder="npr. Slovenija"
                style={fieldError('name') ? { borderColor: 'var(--danger)' } : null} />
              {fieldError('name') && <span style={{ color: 'var(--danger)', fontSize: 12 }}>{fieldError('name')}</span>}
            </div>

            <div className="field col-2">
              <label className="check"><input type="checkbox" checked={f.isEu} onChange={e => set('isEu', e.target.checked)} /> Članica Evropske unije</label>
            </div>

            <div className="form-sec-title"><span dangerouslySetInnerHTML={{ __html: I('settings', 14) }} /> Status</div>
            <div className="field col-2">
              <select className="select" value={f.status} onChange={e => set('status', e.target.value)}>
                <option value="active">Aktivna</option>
                <option value="inactive">Nedejavna</option>
              </select>
            </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' : 'Dodaj državo'}
          </button>
        </div>
      </div>
    </div>
  );
}

function Drzave({ currentUser }) {
  const isAdmin = !!(currentUser && currentUser.role === 'administrator');
  const toast = useToast();
  const [rows, setRows] = useState([]);
  const [currencies, setCurrencies] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [editing, setEditing] = useState(null);

  const load = async () => {
    setLoading(true);
    setError('');
    const { ok, data } = await api('/api/countries');
    if (ok) {
      setRows(data.countries);
    } else {
      setError('Šifranta držav ni bilo mogoče naložiti.');
    }
    setLoading(false);
  };

  useEffect(() => {
    load();
    api('/api/currencies').then(({ ok, data }) => { if (ok) setCurrencies(data.currencies); });
  }, []);

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

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

    setRows(rs => isEdit ? rs.map(r => r.id === data.country.id ? data.country : r) : [data.country, ...rs]);
    toast(isEdit ? 'Država posodobljena' : 'Država dodana: ' + data.country.name, 'check');
    return true;
  };

  return (
    <div>
      {error && <div className="badge dng" style={{ marginBottom: 12 }}>{error}</div>}

      <DataGrid
        columnDefs={COUNTRY_COLS}
        rowData={rows}
        getRowId={(d) => d.id}
        selectable
        exportName="kodila-drzave"
        exportTitle="Šifrant držav"
        searchPlaceholder="Išči po oznaki, imenu…"
        onRowOpen={isAdmin ? (d) => setEditing(d) : undefined}
        actions={isAdmin ? (
          <button className="btn btn-primary btn-sm" onClick={() => setEditing({})} disabled={loading}>
            <span dangerouslySetInnerHTML={{ __html: I('plus', 15) }} /> Nova država
          </button>
        ) : null}
      />

      {isAdmin && editing !== null && (
        <DrzavaForm
          initial={editing}
          currencies={currencies}
          onSave={save}
          onClose={() => setEditing(null)}
        />
      )}
    </div>
  );
}
Object.assign(window, { Drzave });
