import { Typography, Chip, Tooltip } from '@mui/material'
import { AccessTime } from '@mui/icons-material'
import { useMemo } from 'react'
import { useQuery } from '@tanstack/react-query'
import { settingsApi } from '../api/settings'
import { formatDate } from '../utils/formatters'

interface DataFreshnessProps {
  timestamp: string | Date | null | undefined
  refreshInterval?: number
}

export default function DataFreshness({ timestamp, refreshInterval = 5000 }: DataFreshnessProps) {
  const { data: generalSettings } = useQuery({
    queryKey: ['general-settings'],
    queryFn: settingsApi.getGeneralSettings,
  })

  const freshness = useMemo(() => {
    if (!timestamp) return { status: 'unknown', text: 'No data', color: 'default' as const }

    const lastUpdate = new Date(timestamp)
    const now = new Date()
    const ageMs = now.getTime() - lastUpdate.getTime()
    const ageSeconds = Math.floor(ageMs / 1000)

    if (ageSeconds < refreshInterval / 1000) {
      return { status: 'fresh', text: 'Just now', color: 'success' as const }
    } else if (ageSeconds < 60) {
      return { status: 'fresh', text: `${ageSeconds}s ago`, color: 'success' as const }
    } else if (ageSeconds < 300) {
      const minutes = Math.floor(ageSeconds / 60)
      return { status: 'stale', text: `${minutes}m ago`, color: 'warning' as const }
    } else {
      const minutes = Math.floor(ageSeconds / 60)
      return { status: 'outdated', text: `${minutes}m ago`, color: 'error' as const }
    }
  }, [timestamp, refreshInterval])

  if (!timestamp) {
    return (
      <Chip
        icon={<AccessTime />}
        label="No data"
        size="small"
        color="default"
        variant="outlined"
      />
    )
  }

  return (
    <Tooltip title={`Last updated: ${formatDate(timestamp, generalSettings)}`}>
      <Chip
        icon={<AccessTime />}
        label={freshness.text}
        size="small"
        color={freshness.color}
        variant="outlined"
      />
    </Tooltip>
  )
}

