import { useState, type FormEvent } from 'react'
import { post } from '../api'
import { useDialog } from '../components/Dialog'
export function ChangePassword({ onClose, onChange }: { onClose: () => void; onChange: () => void }) {
const dlg = useDialog()
const [oldPwd, setOldPwd] = useState('')
const [newPwd, setNewPwd] = useState('')
const [confirm, setConfirm] = useState('')
const [error, setError] = useState('')
const [busy, setBusy] = useState(false)
async function submit(e: FormEvent) {
e.preventDefault()
if (newPwd.length < 6) { setError('新密码至少 6 位'); return }
if (newPwd !== confirm) { setError('两次输入的新密码不一致'); return }
setError(''); setBusy(true)
try {
await post('/api/auth/change-password', { old_password: oldPwd, new_password: newPwd })
onChange()
onClose()
dlg.toast({ message: '密码已修改', type: 'success' })
} catch (err: any) {
setError(err.message || '修改失败')
} finally { setBusy(false) }
}
return (
<div className="modal-backdrop" onMouseDown={e => { if (e.target === e.currentTarget) onClose() }}>
<div className="modal" style={{ maxWidth: 420 }}>
<div className="modal-head"><h3>修改密码</h3><button className="modal-x" onClick={onClose}>×</button></div>
<form onSubmit={submit} className="modal-body">
<label>原密码<input type="password" value={oldPwd} onChange={e => setOldPwd(e.target.value)} /></label>
<label>新密码<input type="password" value={newPwd} onChange={e => setNewPwd(e.target.value)} placeholder="至少 6 位" /></label>
<label>确认新密码<input type="password" value={confirm} onChange={e => setConfirm(e.target.value)} /></label>
{error && <div className="form-error">{error}</div>}
<div className="modal-actions">
<button type="button" className="btn btn-ghost" onClick={onClose}>取消</button>
<button type="submit" className="btn btn-primary" disabled={busy}>{busy ? '保存中…' : '保存'}</button>
</div>
</form>
</div>
</div>
)
}