import dayjs from 'dayjs'
import type { BadgeVariants } from '@/components/ui/styles/badge.styles'
import type { ExternalSystem, ExternalSystemStatus } from '../types/external-system.types'

export function getExternalSystemStatus(
  system: ExternalSystem,
  now = dayjs(),
): ExternalSystemStatus {
  if (!system.is_active) {
    return 'inactive'
  }

  const startsAt = system.starts_at ? dayjs(system.starts_at) : null
  const endsAt = system.ends_at ? dayjs(system.ends_at) : null

  if (startsAt?.isAfter(now)) {
    return 'upcoming'
  }

  if (endsAt?.isBefore(now)) {
    return 'ended'
  }

  return 'available'
}

export function isExternalSystemAccessible(system: ExternalSystem, now = dayjs()): boolean {
  return getExternalSystemStatus(system, now) === 'available'
}

export function externalSystemStatusLabel(status: ExternalSystemStatus): string {
  switch (status) {
    case 'available':
      return 'Tersedia'
    case 'upcoming':
      return 'Akan Datang'
    case 'ended':
      return 'Tamat'
    case 'inactive':
      return 'Tidak Aktif'
  }
}

export function externalSystemStatusVariant(
  status: ExternalSystemStatus,
): NonNullable<BadgeVariants['variant']> {
  switch (status) {
    case 'available':
      return 'success'
    case 'upcoming':
      return 'pending'
    case 'ended':
      return 'ghost'
    case 'inactive':
      return 'danger'
  }
}

export function formatExternalSystemDateTime(value: string | null): string {
  if (!value) return '-'
  return dayjs(value).format('DD MMM YYYY, HH:mm')
}

export function openExternalSystem(system: ExternalSystem) {
  if (!isExternalSystemAccessible(system)) {
    return
  }

  window.open(
    system.url,
    system.opens_in_new_tab ? '_blank' : '_self',
    'noopener,noreferrer',
  )
}
