import React, { useMemo } from 'react'
import { Text } from '../text/index.js'
import { useLocale } from '../locale/index.js'

/**
 * Renders a persisted Unix ms timestamp as localized text via {@link Text}.
 *
 * @param {object} props
 * @param {number | null | undefined} props.value — Unix ms from form fields / resources
 * @param {'full' | 'long' | 'medium' | 'short'} [props.dateStyle]
 * @param {'full' | 'long' | 'medium' | 'short'} [props.timeStyle]
 * @param {Intl.DateTimeFormatOptions} [props.formatOptions]
 */
export function DateDisplay ({
  value,
  dateStyle,
  timeStyle,
  formatOptions,
  variant = 'default',
  as,
  ...textProps
}) {
  const { language } = useLocale()

  const label = useMemo(() => {
    if (value == null || value === '' || !Number.isFinite(Number(value))) return ''
    const locale = language === 'sv' ? 'sv-SE' : 'en-GB'
    const options = {
      ...(dateStyle != null ? { dateStyle } : {}),
      ...(timeStyle != null ? { timeStyle } : {}),
      ...(dateStyle == null && timeStyle == null && formatOptions == null ? { dateStyle: 'medium' } : {}),
      ...formatOptions,
    }
    return new Intl.DateTimeFormat(locale, options).format(new Date(Number(value)))
  }, [value, language, dateStyle, timeStyle, formatOptions])

  if (!label) return null

  return (
    <Text variant={variant} as={as} {...textProps}>
      {label}
    </Text>
  )
}
