import { useState, useEffect } from 'react'

export default function EmailSettings() {
  const [status,  setStatus]  = useState(null)
  const [testTo,  setTestTo]  = useState('')
  const [testing, setTesting] = useState(false)
  const [testMsg, setTestMsg] = useState(null)

  useEffect(()=>{
    const token = localStorage.getItem('bodytrack_token')||''
    fetch('/api/admin/email/status',{headers:{'X-Auth-Token':token}})
      .then(r=>r.json()).then(setStatus)
  },[])

  const sendTest = async () => {
    if (!testTo) return
    setTesting(true); setTestMsg(null)
    try {
      const token = localStorage.getItem('bodytrack_token')||''
      const r = await fetch('/api/admin/email/test',{
        method:'POST',headers:{'Content-Type':'application/json','X-Auth-Token':token},
        body:JSON.stringify({to:testTo})
      })
      if(!r.ok) throw new Error((await r.json()).detail)
      setTestMsg('✓ Test-E-Mail gesendet!')
    } catch(e){ setTestMsg('✗ Fehler: '+e.message) }
    finally{ setTesting(false) }
  }

  return (
    <div className="card section-gap" style={{marginTop:0}}>
      <div style={{fontWeight:700,fontSize:14,marginBottom:10,display:'flex',alignItems:'center',gap:6}}>
        📧 E-Mail Konfiguration (SMTP)
      </div>
      {!status ? <div className="spinner" style={{width:16,height:16}}/> : (
        <>
          <div style={{padding:'8px 12px',borderRadius:8,marginBottom:12,
            background:status.configured?'var(--accent-light)':'var(--warn-bg)',
            fontSize:12,color:status.configured?'var(--accent-dark)':'var(--warn-text)'}}>
            {status.configured
              ? <>✓ Konfiguriert: <strong>{status.smtp_user}</strong> via {status.smtp_host}</>
              : <>⚠️ Nicht konfiguriert. SMTP-Einstellungen in der <code>.env</code> Datei setzen.</>}
          </div>
          {status.configured && (
            <>
              <div style={{fontSize:11,color:'var(--text3)',marginBottom:10,lineHeight:1.5}}>
                <strong>App-URL:</strong> {status.app_url}<br/>
                <span style={{fontSize:10}}>Für korrekte Links in E-Mails (z.B. Recovery-Links). In .env als APP_URL setzen.</span>
              </div>
              <div style={{display:'flex',gap:8}}>
                <input type="email" className="form-input" placeholder="test@beispiel.de"
                  value={testTo} onChange={e=>setTestTo(e.target.value)} style={{flex:1}}/>
                <button className="btn btn-secondary" onClick={sendTest} disabled={testing}>
                  {testing?'…':'Test'}
                </button>
              </div>
              {testMsg && <div style={{fontSize:12,marginTop:6,
                color:testMsg.startsWith('✓')?'var(--accent)':'#D85A30'}}>{testMsg}</div>}
            </>
          )}
          {!status.configured && (
            <div style={{fontSize:11,color:'var(--text3)',lineHeight:1.6}}>
              Füge folgende Zeilen zur <code>.env</code> Datei hinzu:<br/>
              <code style={{background:'var(--surface2)',padding:'6px 8px',borderRadius:4,
                display:'block',marginTop:6,fontSize:11}}>
                SMTP_HOST=smtp.gmail.com<br/>
                SMTP_PORT=587<br/>
                SMTP_USER=deine@gmail.com<br/>
                SMTP_PASS=dein_app_passwort<br/>
                APP_URL=http://192.168.2.49:3002
              </code>
            </div>
          )}
        </>
      )}
    </div>
  )
}
