/* ============================================================
   KODILA — Admin: Temeljne postavitve
   ============================================================ */

const EMPTY_SETTINGS = {
  mail_host: '', mail_port: '', mail_encryption: 'tls', mail_username: '', mail_password: '',
  mail_from_address: '', mail_from_name: '',
  ai_model: '', ai_api_key: '',
  erp_api_endpoint: '', erp_api_key: '',
  company_city: '', company_country: '',
};

function SecretField({ label, isSet, value, onChange, placeholder }) {
  const [editing, setEditing] = useState(false);
  if (!editing) {
    return (
      <div className="field">
        <label>{label}</label>
        <div className="row" style={{ gap: 10 }}>
          <span className={'badge' + (isSet ? ' ok' : '')} style={{ height: 32 }}>
            <span className="dot"></span>{isSet ? 'Nastavljeno' : 'Ni nastavljeno'}
          </span>
          <button className="btn btn-sm" type="button" onClick={() => setEditing(true)}>
            {isSet ? 'Spremeni' : 'Vnesi'}
          </button>
        </div>
      </div>
    );
  }
  return (
    <div className="field">
      <label>{label}</label>
      <input className="input mono" type="password" autoComplete="new-password" value={value}
        placeholder={placeholder} onChange={e => onChange(e.target.value)} />
    </div>
  );
}

function TemeljnePostavitve() {
  const toast = useToast();
  const [form, setForm] = useState(EMPTY_SETTINGS);
  const [flags, setFlags] = useState({ mail_password_set: false, ai_api_key_set: false, erp_api_key_set: false });
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [errors, setErrors] = useState({});
  const [testTo, setTestTo] = useState('');
  const [testing, setTesting] = useState(false);

  const set = (k, v) => setForm(s => ({ ...s, [k]: v }));

  const load = async () => {
    setLoading(true);
    const { ok, data } = await api('/api/settings');
    if (ok) {
      const s = data.settings;
      setForm(f => ({
        ...f,
        mail_host: s.mail_host || '', mail_port: s.mail_port || '', mail_encryption: s.mail_encryption || 'tls',
        mail_username: s.mail_username || '', mail_from_address: s.mail_from_address || '', mail_from_name: s.mail_from_name || '',
        ai_model: s.ai_model || '', erp_api_endpoint: s.erp_api_endpoint || '',
        company_city: s.company_city || '', company_country: s.company_country || '',
      }));
      setFlags({ mail_password_set: s.mail_password_set, ai_api_key_set: s.ai_api_key_set, erp_api_key_set: s.erp_api_key_set });
    } else {
      toast('Nastavitev ni bilo mogoče naložiti.', 'alert');
    }
    setLoading(false);
  };

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

  const save = async () => {
    setSaving(true);
    setErrors({});
    const { ok, data } = await api('/api/settings', { method: 'PUT', body: JSON.stringify(form) });
    setSaving(false);
    if (!ok) {
      setErrors(data.errors || {});
      toast('Shranjevanje ni uspelo — preveri polja.', 'alert');
      return;
    }
    toast('Nastavitve shranjene', 'check');
    set('mail_password', ''); set('ai_api_key', ''); set('erp_api_key', '');
    setFlags({
      mail_password_set: data.settings.mail_password_set,
      ai_api_key_set: data.settings.ai_api_key_set,
      erp_api_key_set: data.settings.erp_api_key_set,
    });
  };

  const testMail = async () => {
    setTesting(true);
    const { ok, data } = await api('/api/settings/test-mail', { method: 'POST', body: JSON.stringify({ to: testTo || undefined }) });
    setTesting(false);
    if (!ok) {
      const msg = data.error === 'mail_not_configured'
        ? 'Najprej vnesi in shrani strežnik ter vrata.'
        : (data.message || 'Pošiljanje testnega sporočila ni uspelo.');
      toast(msg, 'alert');
      return;
    }
    toast('Testno sporočilo poslano na ' + data.sent_to, 'send');
  };

  const fieldError = (field) => {
    const codes = errors[field];
    return codes && codes.length ? codes.join(', ') : null;
  };

  if (loading) return <div className="muted" style={{ padding: '24px 0' }}>Nalaganje …</div>;

  return (
    <div className="card card-pad">
      <div className="form-grid">
        <div className="form-sec-title"><span dangerouslySetInnerHTML={{ __html: I('send', 14) }} /> Poštni strežnik (SMTP)</div>

        <div className="field">
          <label>Strežnik (host)</label>
          <input className="input" value={form.mail_host} onChange={e => set('mail_host', e.target.value)} placeholder="smtp.kodila.si" />
        </div>
        <div className="field">
          <label>Vrata (port)</label>
          <input className="input mono" value={form.mail_port} onChange={e => set('mail_port', e.target.value)} placeholder="587"
            style={fieldError('mail_port') ? { borderColor: 'var(--danger)' } : null} />
        </div>
        <div className="field">
          <label>Šifriranje</label>
          <select className="select" value={form.mail_encryption} onChange={e => set('mail_encryption', e.target.value)}>
            <option value="tls">STARTTLS</option>
            <option value="ssl">SSL</option>
            <option value="none">Brez</option>
          </select>
        </div>
        <div className="field">
          <label>Uporabniško ime</label>
          <input className="input" value={form.mail_username} onChange={e => set('mail_username', e.target.value)} placeholder="intranet@kodila.si" />
        </div>
        <SecretField label="Geslo" isSet={flags.mail_password_set} value={form.mail_password}
          onChange={v => set('mail_password', v)} placeholder="Novo geslo strežnika" />
        <div className="field">
          <label>Od (e-poštni naslov)</label>
          <input className="input" value={form.mail_from_address} onChange={e => set('mail_from_address', e.target.value)} placeholder="intranet@kodila.si"
            style={fieldError('mail_from_address') ? { borderColor: 'var(--danger)' } : null} />
        </div>
        <div className="field">
          <label>Od (prikazno ime)</label>
          <input className="input" value={form.mail_from_name} onChange={e => set('mail_from_name', e.target.value)} placeholder="KODILA Intranet" />
        </div>

        <div className="field col-2" style={{ flexDirection: 'row', alignItems: 'flex-end', gap: 10 }}>
          <div style={{ flex: 1 }}>
            <label>Testni prejemnik (neobvezno)</label>
            <input className="input" value={testTo} onChange={e => setTestTo(e.target.value)} placeholder="tvoj.naslov@kodila.si" />
          </div>
          <button className="btn" type="button" onClick={testMail} disabled={testing}>
            <span dangerouslySetInnerHTML={{ __html: I('send', 16) }} /> {testing ? 'Pošiljam …' : 'Testiraj povezavo'}
          </button>
        </div>

        <div className="form-sec-title"><span dangerouslySetInnerHTML={{ __html: I('layers', 14) }} /> AI model</div>
        <div className="field">
          <label>Model</label>
          <input className="input" value={form.ai_model} onChange={e => set('ai_model', e.target.value)} placeholder="npr. claude-sonnet-4-6" />
        </div>
        <SecretField label="API ključ" isSet={flags.ai_api_key_set} value={form.ai_api_key}
          onChange={v => set('ai_api_key', v)} placeholder="sk-…" />

        <div className="form-sec-title"><span dangerouslySetInnerHTML={{ __html: I('box', 14) }} /> ERP povezava</div>
        <div className="field col-2">
          <label>API endpoint</label>
          <input className="input mono" value={form.erp_api_endpoint} onChange={e => set('erp_api_endpoint', e.target.value)} placeholder="https://erp.kodila.si/api"
            style={fieldError('erp_api_endpoint') ? { borderColor: 'var(--danger)' } : null} />
        </div>
        <SecretField label="API ključ (neobvezno)" isSet={flags.erp_api_key_set} value={form.erp_api_key}
          onChange={v => set('erp_api_key', v)} placeholder="API ključ ERP sistema" />

        <div className="form-sec-title"><span dangerouslySetInnerHTML={{ __html: I('store', 14) }} /> Lokacija sedeža podjetja</div>
        <div className="field">
          <label>Kraj</label>
          <input className="input" value={form.company_city} onChange={e => set('company_city', e.target.value)} placeholder="npr. Murska Sobota" />
        </div>
        <div className="field">
          <label>Država</label>
          <input className="input" value={form.company_country} onChange={e => set('company_country', e.target.value)} placeholder="npr. Slovenija" />
        </div>
      </div>

      <div className="row mt-24" style={{ justifyContent: 'flex-end' }}>
        <button className="btn btn-primary" onClick={save} disabled={saving}>
          <span dangerouslySetInnerHTML={{ __html: I('save', 16) }} /> {saving ? 'Shranjujem …' : 'Shrani spremembe'}
        </button>
      </div>
    </div>
  );
}
Object.assign(window, { TemeljnePostavitve });
