'use client'

// Signed-in devices for the customer's own account (Account → Change Password).
import { useCallback, useEffect, useState } from 'react'
import { useLocale, useTranslations } from 'next-intl'

interface SessionItem {
  id: string
  device: string
  ipAddress: string | null
  current: boolean
  active: boolean
  createdSecondsAgo: number
  lastActiveSecondsAgo: number
  endedSecondsAgo: number | null
  endReason: string | null
}

const REASONS = [
  'logout', 'password_changed', 'idle_timeout', 'expired', 'forced',
  'token_reuse', 'device_mismatch', 'replaced', 'terminated',
] as const

export default function SignedInDevices() {
  const t = useTranslations('Account.sessions')
  const locale = useLocale()
  const [sessions, setSessions] = useState<SessionItem[] | null>(null)
  const [error, setError] = useState('')
  const [busy, setBusy] = useState<string | null>(null)

  const ago = useCallback(
    (seconds: number) => {
      if (seconds < 60) return t('justNow')
      const rtf = new Intl.RelativeTimeFormat(locale, { numeric: 'auto' })
      if (seconds >= 86400) return rtf.format(-Math.floor(seconds / 86400), 'day')
      if (seconds >= 3600) return rtf.format(-Math.floor(seconds / 3600), 'hour')
      return rtf.format(-Math.floor(seconds / 60), 'minute')
    },
    [locale, t],
  )

  const load = useCallback(async () => {
    try {
      const res = await fetch('/api/frontend/auth/sessions', { cache: 'no-store' })
      const data = await res.json()
      if (!res.ok || !data.success) throw new Error()
      setSessions(data.data.sessions)
      setError('')
    } catch {
      setError(t('loadFailed'))
    }
  }, [t])

  useEffect(() => {
    // eslint-disable-next-line react-hooks/set-state-in-effect -- initial fetch
    load()
  }, [load])

  async function revoke(body: { action: 'revoke'; id: string } | { action: 'revoke_others' }) {
    setBusy(body.action === 'revoke' ? body.id : 'others')
    try {
      const res = await fetch('/api/frontend/auth/sessions', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(body),
      })
      const data = await res.json()
      if (!res.ok || !data.success) throw new Error()
      await load()
    } catch {
      setError(t('actionFailed'))
    } finally {
      setBusy(null)
    }
  }

  const reason = (r: string | null) =>
    r && (REASONS as readonly string[]).includes(r) ? t(`reasons.${r as (typeof REASONS)[number]}`) : r ?? ''

  const active = sessions?.filter((s) => s.active) ?? []
  const history = sessions?.filter((s) => !s.active) ?? []
  const others = active.filter((s) => !s.current)

  return (
    <section className="mt-8 rounded-2xl border border-gray-200 bg-white p-5 sm:p-6">
      <div className="flex flex-wrap items-start justify-between gap-3">
        <div>
          <h2 className="text-lg font-semibold text-gray-900">{t('title')}</h2>
          <p className="mt-1 text-sm text-gray-500">{t('description')}</p>
        </div>
        {others.length > 0 && (
          <button
            type="button"
            onClick={() => revoke({ action: 'revoke_others' })}
            disabled={busy !== null}
            className="rounded-lg border border-red-200 px-3 py-2 text-sm font-medium text-red-600 hover:bg-red-50 disabled:opacity-60"
          >
            {busy === 'others' ? t('signingOut') : t('signOutOthers')}
          </button>
        )}
      </div>

      {error && <p className="mt-4 rounded-lg bg-red-50 px-3 py-2 text-sm text-red-600">{error}</p>}
      {sessions === null && !error && <p className="mt-4 text-sm text-gray-500">{t('loading')}</p>}

      <ul className="mt-4 flex flex-col gap-3">
        {active.map((s) => (
          <li key={s.id} className="flex items-start justify-between gap-3 rounded-xl bg-gray-50 p-3">
            <div className="min-w-0">
              <p className="flex flex-wrap items-center gap-2 text-sm font-medium text-gray-900">
                {s.device}
                {s.current && (
                  <span className="rounded-full bg-green-100 px-2 py-0.5 text-xs text-green-700">{t('thisDevice')}</span>
                )}
              </p>
              <p className="mt-0.5 text-xs text-gray-500">
                {s.ipAddress ?? t('unknownIp')} · {t('signedIn', { time: ago(s.createdSecondsAgo) })} ·{' '}
                {t('lastActive', { time: ago(s.lastActiveSecondsAgo) })}
              </p>
            </div>
            {!s.current && (
              <button
                type="button"
                onClick={() => revoke({ action: 'revoke', id: s.id })}
                disabled={busy !== null}
                className="shrink-0 text-sm font-medium text-red-600 hover:underline disabled:opacity-60"
              >
                {busy === s.id ? t('signingOut') : t('signOut')}
              </button>
            )}
          </li>
        ))}
      </ul>

      {history.length > 0 && (
        <div className="mt-6">
          <h3 className="text-sm font-semibold text-gray-900">{t('recentTitle')}</h3>
          <ul className="mt-2 divide-y divide-gray-100">
            {history.map((s) => {
              const alarming = s.endReason === 'token_reuse' || s.endReason === 'device_mismatch'
              return (
                <li key={s.id} className="flex items-start justify-between gap-3 py-2.5">
                  <div className="min-w-0">
                    <p className="text-sm text-gray-800">{s.device}</p>
                    <p className="mt-0.5 text-xs text-gray-500">
                      {s.ipAddress ?? t('unknownIp')} · {t('signedIn', { time: ago(s.createdSecondsAgo) })}
                    </p>
                  </div>
                  <span className={`shrink-0 text-end text-xs ${alarming ? 'text-red-600' : 'text-gray-500'}`}>
                    {reason(s.endReason)}
                    {s.endedSecondsAgo !== null && (
                      <>
                        <br />
                        {ago(s.endedSecondsAgo)}
                      </>
                    )}
                  </span>
                </li>
              )
            })}
          </ul>
        </div>
      )}
    </section>
  )
}
