import { clsx, type ClassValue } from 'clsx'
import { twMerge } from 'tailwind-merge'
import dayjs from 'dayjs'
import numeral from 'numeral'

// 合并类名
export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs))
}

// 计算年龄
export function calculateAge(year: string, month: string, day: string) {
  const birthDate = dayjs(`${year}-${month}-${day}`)
  const today = dayjs()
  return today.diff(birthDate, 'year')
}

export function calculateAgeByBirthday(birthday?: string) {
  if (!birthday) return ''
  const birthDate = dayjs(birthday)
  const today = dayjs()
  return today.diff(birthDate, 'year')
}

// 获取月份天数
export function getDaysInMonth(year: string, month: string) {
  return Array.from({ length: dayjs(`${year}-${month}`).daysInMonth() }, (_, i) =>
    `${i + 1}`.padStart(2, '0')
  )
}

// 延迟函数
export function delay(ms: number) {
  return new Promise((resolve) => setTimeout(resolve, ms))
}

// 加载图片
export async function loadImageAsync(url: string) {
  return new Promise((resolve, reject) => {
    const img = new Image()
    img.crossOrigin = 'anonymous'
    img.onload = () => resolve(img)
    img.onerror = () => reject(new Error(`Failed to load image: ${url}`))
    img.src = url
  })
}

// 数字简化显示（K/M/B格式）
export function formatNumberToKMB(number: number) {
  if (number >= 1000000000) {
    return numeral(Math.floor(number / 100000000) / 10).format('0.0') + 'B'
  }
  if (number >= 1000000) {
    return numeral(Math.floor(number / 100000) / 10).format('0.0') + 'M'
  }
  if (number >= 1000) {
    return numeral(Math.floor(number / 100) / 10).format('0.0') + 'K'
  }
  return number || 0
}

// 根据时间戳（毫秒）获取年龄
export function getAge(birthday: number) {
  if (!birthday) return 0
  const birthDate = dayjs(birthday)
  const today = dayjs()
  let age = today.year() - birthDate.year()
  // 如果今年还没过生日，年龄减一
  if (
    today.month() < birthDate.month() ||
    (today.month() === birthDate.month() && today.date() < birthDate.date())
  ) {
    age--
  }
  return age
}

export function getConversationTime(timestamp: number) {
  const now = dayjs()
  const timestampDate = dayjs(timestamp)
  // 当天显示HH:mm
  if (now.isSame(timestampDate, 'day')) {
    return timestampDate.format('HH:mm')
  }
  // 昨天显示昨天HH:mm
  if (now.subtract(1, 'day').isSame(timestampDate, 'day')) {
    return 'Yesterday ' + timestampDate.format('HH:mm')
  }
  // 今年显示MM-DD
  if (now.isSame(timestampDate, 'year')) {
    return timestampDate.format('MM-DD')
  }
  return timestampDate.format('YYYY-MM-DD')
}

// 格式化心动等级值
export function formatHeartbeatLevel(value: number) {
  return `${value.toFixed(1)}℃`
}

export function openApp(schemeURI: string) {
  const schemeUrl = schemeURI
  const downloadUrl = 'https://crushlevel.com/download' // 下载页 URL
  const startTime = Date.now()
  window.location.href = schemeUrl
  setTimeout(() => {
    if (Date.now() - startTime < 2100) {
      // 唤起成功
      return
    }
    window.location.href = downloadUrl // 失败跳转下载
  }, 2000)
}

// 毫秒转mm:ss, 如果是小时则为hh:mm
export function durationText(duration: number) {
  const hours = Math.floor(duration / 3600000)
  const minutes = Math.floor((duration % 3600000) / 60000)
  const seconds = Math.floor((duration % 60000) / 1000)

  if (hours > 0) {
    return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
  } else if (minutes > 0) {
    return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
  } else {
    return `00:${seconds.toString().padStart(2, '0')}`
  }
}
