import type { Metadata } from 'next'
import { setRequestLocale, getTranslations } from 'next-intl/server'
import { redirect } from '@/i18n/navigation'
import { getSession } from '@/lib/session'
import { getSecurityHistory } from '@/lib/security-history'
import { wowAccountLabel } from '@/lib/bnet'
import { PageShell } from '@/components/PageShell'
import { ServiceBox } from '@/components/ServiceBox'

export const dynamic = 'force-dynamic'

export async function generateMetadata({ params }: { params: Promise<{ locale: string }> }): Promise<Metadata> {
  const { locale } = await params
  const t = await getTranslations({ locale, namespace: 'History' })
  return { title: t('security.pageTitle') }
}

/** Fecha en formato HH:MM:SS DD-MM-YYYY (como el diseño). */
function fmt(d: Date): string {
  const p = (n: number) => String(n).padStart(2, '0')
  return `${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())} ${p(d.getDate())}-${p(d.getMonth() + 1)}-${d.getFullYear()}`
}

/** Celda «Usuario»: cuenta de juego (WOW1) + cuenta Battle.net (email) debajo. */
function UserCell({ label, bnet }: { label: string; bnet: string }) {
  return (
    <td>
      <span>{label}</span>
      {bnet && (
        <>
          <br />
          <span className="second-brown small-font">{bnet}</span>
        </>
      )}
    </td>
  )
}

export default async function SecurityHistoryPage({ params }: { params: Promise<{ locale: string }> }) {
  const { locale } = await params
  setRequestLocale(locale)
  const t = await getTranslations('History')

  const session = await getSession()
  if (!session.bnetId) redirect({ href: '/log-in', locale })
  if (!session.username) redirect({ href: '/select-account', locale })

  const bnetEmail = session.bnetEmail || ''
  const displayUser = wowAccountLabel(session.username || '') // «15#1» → «WOW1»
  const { activity, realm, web } = await getSecurityHistory(session.accountId!, displayUser, bnetEmail)

  return (
    <PageShell title={t('security.pageTitle')}>
      <ServiceBox>
        <br />
        <p>{t('security.intro1')}</p>
        <p>{t('security.intro2')}</p>
        <p>
          {t('security.intro3')}
        </p>
        <br />
        <p>
          <span>{t('security.activityTitle')}</span>
        </p>
        <p>{t('security.activityDesc')}</p>
        <br />
        <p>
          <span>{t('security.realmTitle')}</span>
        </p>
        <p>
          {t.rich('security.realmDesc', { u: (c) => <u>{c}</u> })}
        </p>
        <br />
        <p>
          <span>{t('security.webTitle')}</span>
        </p>
        <p>{t('security.webDesc')}</p>
      </ServiceBox>

      {/* Historial de actividad */}
      <div className="box-content">
        <div className="title-box-content">
          <h2>{t('security.activityTitle')}</h2>
        </div>
        <div className="body-box-content centered">
          {activity.length === 0 ? (
            <table className="max-center-table-aligned2">
              <tbody>
                <tr>
                  <td>
                    <span>{t('security.noActivity')}</span>
                  </td>
                </tr>
              </tbody>
            </table>
          ) : (
            <table className="max-center-table-aligned2">
              <tbody>
                <tr>
                  <th>{t('security.thUser')}</th>
                  <th>{t('security.thAction')}</th>
                  <th>IP</th>
                  <th>{t('security.thDate')}</th>
                </tr>
                {activity.map((a, i) => (
                  <tr key={i}>
                    <UserCell label={a.user} bnet={bnetEmail} />
                    <td>
                      <span>{t(`security.action.${a.actionKey}`)}</span>
                    </td>
                    <td className="long-td">
                      <span>{a.ip}</span>
                    </td>
                    <td>
                      <span>{fmt(a.date)}</span>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>
      </div>

      {/* Historial de conexiones (Reino) */}
      <div className="box-content">
        <div className="title-box-content">
          <h2>{t('security.realmTitle')}</h2>
        </div>
        <div className="body-box-content centered">
          {realm.length === 0 ? (
            <table className="max-center-table-aligned">
              <tbody>
                <tr>
                  <td>
                    <span>{t('security.noConnections')}</span>
                  </td>
                </tr>
              </tbody>
            </table>
          ) : (
            <table className="max-center-table-aligned">
              <tbody>
                <tr>
                  <th>IP</th>
                  <th>{t('security.thDate')}</th>
                </tr>
                {realm.map((c, i) => (
                  <tr key={i}>
                    <td className="long-td">
                      <span>{c.ip}</span>
                    </td>
                    <td>
                      <span>{fmt(c.date)}</span>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>
      </div>

      {/* Historial de conexiones (Web) */}
      <div className="box-content">
        <div className="title-box-content">
          <h2>{t('security.webTitle')}</h2>
        </div>
        <div className="body-box-content centered">
          {web.length === 0 ? (
            <table className="max-center-table-aligned">
              <tbody>
                <tr>
                  <td>
                    <span>{t('security.noConnections')}</span>
                  </td>
                </tr>
              </tbody>
            </table>
          ) : (
            <table className="max-center-table-aligned">
              <tbody>
                <tr>
                  <th>{t('security.thUser')}</th>
                  <th>{t('security.thStatus')}</th>
                  <th>IP</th>
                  <th>{t('security.thDate')}</th>
                </tr>
                {web.map((c, i) => (
                  <tr key={i}>
                    <UserCell label={c.user} bnet={bnetEmail} />
                    <td>
                      <span className={c.statusKey === 'wrongPassword' ? 'red-info2' : ''}>
                        {c.statusKey === 'other' ? c.statusRaw : t(`security.webStatus.${c.statusKey}`)}
                      </span>
                    </td>
                    <td className="long-td">
                      <span>{c.ip}</span>
                    </td>
                    <td>
                      <span>{fmt(c.date)}</span>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>
      </div>
    </PageShell>
  )
}
