/* global React */
const { useState, useEffect } = React;

function SettingsScreen() {
  const [smtp, setSmtp] = useState({ host: '', port: 465, user: '', pass: '', to: '', from: '' });
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [testing, setTesting] = useState(false);
  const toast = useToast();

  useEffect(() => {
    fetch('/api/pd/api/config', { headers: authHeader() })
      .then(r => r.json())
      .then(cfg => {
        if (cfg.smtp) setSmtp(s => ({ ...s, ...cfg.smtp }));
      })
      .catch(() => toast('Could not load email configuration', 'danger'))
      .finally(() => setLoading(false));
  }, []);

  const save = async (e) => {
    e.preventDefault();
    setSaving(true);
    try {
      // Load full config first so we only update the smtp field
      const cfg = await fetch('/api/pd/api/config', { headers: authHeader() }).then(r => r.json());
      await fetch('/api/pd/api/config', {
        method: 'POST',
        headers: { ...authHeader(), 'Content-Type': 'application/json' },
        body: JSON.stringify({ ...cfg, smtp }),
      });
      toast('Email configuration saved', 'success');
    } catch (err) {
      toast('Failed to save: ' + err.message, 'danger');
    }
    setSaving(false);
  };

  const sendTest = async () => {
    if (!smtp.host || !smtp.to) { toast('Fill in host and To address first', 'danger'); return; }
    setTesting(true);
    try {
      const r = await fetch('/api/pd/api/config/test-email', {
        method: 'POST',
        headers: { ...authHeader(), 'Content-Type': 'application/json' },
        body: JSON.stringify({ smtp }),
      });
      if (!r.ok) { const e = await r.json(); throw new Error(e.error || r.statusText); }
      toast('Test email sent to ' + smtp.to, 'success');
    } catch (err) {
      toast('Test failed: ' + err.message, 'danger');
    }
    setTesting(false);
  };

  const set = (field) => (e) => setSmtp(s => ({ ...s, [field]: e.target.value }));

  return (
    <div style={{ padding: '28px 32px 64px', maxWidth: 860, margin: '0 auto' }}>
      <div style={{ marginBottom: 28 }}>
        <h1 style={{ fontFamily: 'var(--s-font-display)', fontWeight: 400, fontSize: 26, letterSpacing: '-0.01em', marginBottom: 6 }}>Settings</h1>
        <p style={{ fontSize: 13, color: 'var(--s-fg-3)' }}>Portal-level configuration shared across all tools.</p>
      </div>

      <form onSubmit={save} style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
        {/* Email notifications */}
        <div className="card" style={{ padding: 24 }}>
          <SectionHead
            title="Email notifications"
            hint="Sync summaries are sent after each Pipedrive run"
            right={
              <Button size="sm" variant="secondary" type="button"
                icon={<Icon d={I.mail} size={12}/>}
                loading={testing}
                onClick={sendTest}>
                Send test
              </Button>
            }
          />

          {loading ? (
            <div style={{ padding: 32, textAlign: 'center', color: 'var(--s-fg-3)', fontSize: 13 }}>Loading…</div>
          ) : (
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
              <Input label="SMTP host" value={smtp.host} onChange={set('host')} placeholder="mail.example.com"/>
              <Input label="Port" type="number" value={smtp.port} onChange={set('port')} placeholder="465"/>
              <Input label="Username" value={smtp.user} onChange={set('user')} autoComplete="off"/>
              <Input label="Password" type="password" value={smtp.pass} onChange={set('pass')} autoComplete="new-password"/>
              <Input label="To (recipient)" type="email" value={smtp.to} onChange={set('to')} placeholder="you@example.com"/>
              <Input label="From alias" value={smtp.from} onChange={set('from')} placeholder="noreply@example.com"/>
            </div>
          )}
        </div>

        <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
          <Button variant="primary" type="submit" loading={saving} icon={<Icon d={I.check} size={13}/>}>
            Save settings
          </Button>
        </div>
      </form>
    </div>
  );
}

window.SettingsScreen = SettingsScreen;
