import { cookies } from 'next/headers'
import { redirect } from 'next/navigation'
import { verifySharedJwt } from '@/lib/jwt'
import Header from '@/components/Header'
import ChangePasswordForm from './change-password-form'
import EmailEditor from './email-editor'

export default async function ProfilePage() {
  const cookieStore = await cookies()
  const token = cookieStore.get('tlyq_session')?.value
  if (!token) redirect('/login')

  const session = verifySharedJwt(token)
  if (!session) redirect('/login')

  return (
    <div style={{ minHeight: '100vh', background: 'var(--bg)' }}>
      <Header backLabel="个人信息" />

      <div style={{ display: 'flex', justifyContent: 'center', paddingTop: 56 }}>
        <div style={{ width: 480, display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div style={{ background: 'var(--bg-card)', border: '1px solid var(--border)', borderRadius: 12, padding: 28, boxShadow: '0 1px 3px rgba(0,0,0,0.06), 0 1px 2px rgba(0,0,0,0.04)' }}>
            <h2 style={{ fontSize: 17, fontWeight: 700, margin: '0 0 18px', color: 'var(--text)' }}>账户信息</h2>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
              <div>
                <div style={{ fontSize: 12, color: 'var(--text-muted)', marginBottom: 3 }}>用户名</div>
                <div style={{ fontSize: 14, fontWeight: 500, color: 'var(--text)' }}>{session.username}</div>
              </div>
              <div>
                <div style={{ fontSize: 12, color: 'var(--text-muted)', marginBottom: 3 }}>显示名</div>
                <div style={{ fontSize: 14, fontWeight: 500, color: 'var(--text)' }}>{session.displayName}</div>
              </div>
              <div>
                <div style={{ fontSize: 12, color: 'var(--text-muted)', marginBottom: 3 }}>认证方式</div>
                <div style={{ fontSize: 14, fontWeight: 500, color: 'var(--text)' }}>LLDAP 统一认证</div>
              </div>
              <div>
                <div style={{ fontSize: 12, color: 'var(--text-muted)', marginBottom: 3 }}>会话有效期</div>
                <div style={{ fontSize: 14, fontWeight: 500, color: 'var(--text)' }}>{(() => { const d = new Date(session.exp * 1000); return `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')} ${String(d.getHours()).padStart(2,'0')}:${String(d.getMinutes()).padStart(2,'0')}:${String(d.getSeconds()).padStart(2,'0')}` })()}</div>
              </div>
            </div>
            <div style={{ marginTop: 18, paddingTop: 18, borderTop: '1px solid var(--border)' }}>
              <EmailEditor />
            </div>
          </div>
          <ChangePasswordForm />
        </div>
      </div>
    </div>
  )
}
