'use client'

import i18n from '@/i18n/config'
import { formatDateTime } from '@/utils/formatDate'

export function formatViews(views: number): string {
    const currentLang = i18n.language || 'zh-TW'
    const isChinese = currentLang.startsWith('zh')
    const tenThousandLabel = i18n.t('explore.tenThousand')
    if (isChinese) {
        if (views >= 10000) {
            const tenThousand = views / 10000
            if (tenThousand % 1 === 0) {
                return `${tenThousand}${tenThousandLabel}`
            }
            const floored = Math.floor(tenThousand * 10) / 10
            return `${floored.toFixed(1)}${tenThousandLabel}`
        }
    } else {
        if (views >= 1000) {
            const thousands = views / 1000
            if (thousands % 1 === 0) {
                return `${thousands}${tenThousandLabel}`
            }
            const floored = Math.floor(thousands * 10) / 10
            return `${floored.toFixed(1)}${tenThousandLabel}`
        }
    }
    return views.toLocaleString()
}

function formatYmd(d: Date): string {
    const y = d.getFullYear()
    const m = String(d.getMonth() + 1).padStart(2, '0')
    const day = String(d.getDate()).padStart(2, '0')
    return `${y}/${m}/${day}`
}

/** 將 started_at（Unix 秒或 ISO）格式為 yyyy/mm/dd */
export function formatLastStreamDate(input?: string | number | Date | null): string {
    if (input == null) return ''
    if (input instanceof Date) {
        if (!Number.isFinite(input.getTime())) return ''
        return formatYmd(input)
    }
    const epochMs = parseStartedAtToEpochMs(input)
    if (epochMs != null) return formatYmd(new Date(Number(epochMs)))
    if (typeof input === 'string') {
        const parsed = Date.parse(input.trim())
        if (Number.isFinite(parsed)) return formatYmd(new Date(parsed))
    }
    return ''
}

/** 未滿此時間顯示相對時間（如「5 分鐘前」），否則顯示日期 */
const ONE_MONTH_MS = 30 * 24 * 60 * 60 * 1000

function parseInputToEpochMs(input?: string | number | Date | null): number | null {
    if (input == null) return null
    if (input instanceof Date) {
        const t = input.getTime()
        return Number.isFinite(t) ? t : null
    }
    const epoch = parseStartedAtToEpochMs(input)
    if (epoch != null) return Number(epoch)
    if (typeof input === 'string') {
        const parsed = Date.parse(input.trim())
        if (Number.isFinite(parsed)) return parsed
    }
    return null
}

/** 上次／本場開播的完整本地時間（供 title / tooltip） */
export function formatStreamStartedAtDateTime(
    input?: string | number | Date | null
): string {
    const ts = parseInputToEpochMs(input)
    if (ts == null) return ''
    return formatDateTime(new Date(Number(ts)).toISOString())
}

function formatUnixToYmd(input?: string | number | null): string {
    if (input == null || input === '') return ''
    const n = Number(input)
    if (!Number.isFinite(n) || n <= 0) return ''
    const ms = n < 1_000_000_000_000 ? n * 1000 : n
    const d = new Date(ms)
    const y = d.getFullYear()
    const m = String(d.getMonth() + 1).padStart(2, '0')
    const day = String(d.getDate()).padStart(2, '0')
    return `${y}-${m}-${day}`
}

/** user_groups.join_at（Unix 秒或毫秒）→ 本地 yyyy-mm-dd */
export function formatGroupMemberJoinAt(input?: string | number | null): string {
    return formatUnixToYmd(input)
}

/** 申請時間等：yyyy-mm-dd hh:mm:ss */
export function formatGroupMemberJoinDateTime(input?: string | number | null): string {
    if (input == null || input === '') return ''
    const n = Number(input)
    if (!Number.isFinite(n) || n <= 0) return ''
    const ms = n < 1_000_000_000_000 ? n * 1000 : n
    return formatDateTime(new Date(ms).toISOString())
}

/** 本場開播顯示用：未滿 1 個月為相對時間（如「5 分鐘前」），否則為在地化日期 */
export function formatLiveStartedDatePart(
    input?: string | number | Date | null,
    nowMs: number = Date.now()
): string {
    const ts = parseInputToEpochMs(input)
    if (ts == null) return ''
    const diffMs = Math.max(0, nowMs - ts)
    if (diffMs < ONE_MONTH_MS) {
        return getRelativeTime(input, nowMs)
    }
    return new Intl.DateTimeFormat(undefined, {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
    }).format(new Date(ts))
}

/** 距今未滿 1 個月：相對時間；滿 1 個月：yyyy/mm/dd */
export function formatLastStreamAtLabel(
    input?: string | number | Date | null,
    nowMs: number = Date.now()
): string {
    const ts = parseInputToEpochMs(input)
    if (ts == null) return ''
    const diffMs = Math.max(0, nowMs - ts)
    const datePart =
        diffMs >= ONE_MONTH_MS ? formatYmd(new Date(ts)) : getRelativeTime(input, nowMs)
    if (!datePart) return ''
    return i18n.t('room.lastStreamAt', { date: datePart })
}

export function getRelativeTime(
    input?: string | number | Date | null,
    nowMs: number = Date.now()
): string {
    const ts = parseInputToEpochMs(input)
    if (ts == null) return ''

    const diffMs = Math.max(0, nowMs - ts)
    const diffSec = Math.floor(diffMs / 1000)
    if (diffSec < 60) {
        return i18n.t('room.time.secondsAgo', { count: diffSec })
    }
    const diffMin = Math.floor(diffSec / 60)
    if (diffMin < 60) {
        return i18n.t('room.time.minutesAgo', { count: diffMin })
    }
    const diffHour = Math.floor(diffMin / 60)
    if (diffHour < 24) {
        return i18n.t('room.time.hoursAgo', { count: diffHour })
    }

    const from = new Date(ts)
    const to = new Date(nowMs)
    const monthDiff =
        (to.getFullYear() - from.getFullYear()) * 12 + (to.getMonth() - from.getMonth())
    if (monthDiff >= 1) {
        return i18n.t('room.time.monthsAgo', { count: monthDiff })
    }

    const diffDay = Math.floor(diffHour / 24)
    return i18n.t('room.time.daysAgo', { count: Math.max(1, diffDay) })
}

function formatHmsFromSeconds(sec: bigint): string {
    const s = sec < 0n ? 0n : sec
    const h = s / 3600n
    const m = (s % 3600n) / 60n
    const ss = s % 60n
    const hh = h.toString().padStart(2, '0')
    const mm = m.toString().padStart(2, '0')
    const sss = ss.toString().padStart(2, '0')
    return `${hh}:${mm}:${sss}`
}

function normalizeEpochMs(v: bigint): bigint {
    if (v < 1_000_000_000_000n) return v * 1000n
    if (v > 1_000_000_000_000_000_000n) return v / 1_000_000n
    if (v > 1_000_000_000_000_000n) return v / 1000n
    return v
}

function parseStartedAtToEpochMs(startedAt: unknown): bigint | null {
    if (startedAt == null) return null
    if (typeof startedAt === 'bigint') return normalizeEpochMs(startedAt)
    if (typeof startedAt === 'number') {
        if (!Number.isFinite(startedAt)) return null
        return normalizeEpochMs(BigInt(Math.trunc(startedAt)))
    }
    if (typeof startedAt === 'string') {
        const s = startedAt.trim()
        if (!s) return null
        if (/^\d{1,2}:\d{2}(:\d{2})?$/.test(s)) return null
        if (/^\d+$/.test(s)) return normalizeEpochMs(BigInt(s))
        const parsed = Date.parse(s)
        if (Number.isFinite(parsed)) return BigInt(parsed)
        const m = s.match(/^(\d{2})-(\d{2})\s+(\d{2}):(\d{2})$/)
        if (m) {
            const year = new Date().getFullYear()
            const iso = `${year}-${m[1]}-${m[2]}T${m[3]}:${m[4]}:00`
            const p2 = Date.parse(iso)
            if (Number.isFinite(p2)) return BigInt(p2)
        }

        return null
    }
    return null
}

export function formatLiveDuration(startedAt: unknown, nowMs: number = Date.now()): string {
    if (typeof startedAt === 'string') {
        const s = startedAt.trim()
        if (/^\d{1,2}:\d{2}:\d{2}$/.test(s)) return s
        if (/^\d{1,2}:\d{2}$/.test(s)) return `00:${s}`
    }
    const startMs = parseStartedAtToEpochMs(startedAt)
    if (!startMs) return ''
    const now = BigInt(Math.max(0, Math.trunc(nowMs)))
    const diffMs = now > startMs ? now - startMs : 0n
    const diffSec = diffMs / 1000n
    return formatHmsFromSeconds(diffSec)
}

