import type {
  MachineStateCode,
  MachineUsageSummary,
} from '../../../../entities/machine/model/types'

export const analyticsStateMeta: Record<
  MachineStateCode,
  {
    label: string
    color: string
    className: string
  }
> = {
  MOVING: {
    label: 'В движении',
    color: '#33b343',
    className: 'moving',
  },
  ENGINE_ON: {
    label: 'Холостой ход',
    color: '#ff9f43',
    className: 'engine-on',
  },
  IDLE: {
    label: 'Простой',
    color: '#8c96aa',
    className: 'idle',
  },
  NO_DATA: {
    label: 'Нет данных',
    color: '#e04f5f',
    className: 'no-data',
  },
}

export function formatAnalyticsDuration(totalSeconds: number) {
  const normalizedSeconds = Math.max(0, Math.floor(totalSeconds))
  const totalMinutes = Math.floor(normalizedSeconds / 60)
  const hours = Math.floor(totalMinutes / 60)
  const minutes = totalMinutes % 60

  if (hours > 0) {
    return `${hours} ч ${minutes} мин`
  }

  if (totalMinutes > 0) {
    return `${totalMinutes} мин`
  }

  return `${normalizedSeconds} сек`
}

export function formatDetailedDuration(totalSeconds: number) {
  const normalizedSeconds = Math.max(0, Math.floor(totalSeconds))
  const totalMinutes = Math.floor(normalizedSeconds / 60)
  const hours = Math.floor(totalMinutes / 60)
  const minutes = totalMinutes % 60
  const seconds = normalizedSeconds % 60

  if (hours > 0) {
    return seconds > 0
      ? `${hours} ч ${minutes} мин ${seconds} сек`
      : `${hours} ч ${minutes} мин`
  }

  if (totalMinutes > 0) {
    return seconds > 0
      ? `${totalMinutes} мин ${seconds} сек`
      : `${totalMinutes} мин`
  }

  return `${seconds} сек`
}

export function formatAnalyticsDateTime(date: string | number) {
  return new Intl.DateTimeFormat('ru-RU', {
    day: '2-digit',
    month: '2-digit',
    year: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  }).format(new Date(date))
}

export function formatAnalyticsDate(date: string | number) {
  return new Intl.DateTimeFormat('ru-RU', {
    day: '2-digit',
    month: '2-digit',
  }).format(new Date(date))
}

export function formatAnalyticsPercent(value: number) {
  return `${Math.round(value)}%`
}

export function secondsToHours(seconds: number) {
  return Number((seconds / 3600).toFixed(2))
}

export function getSummaryTotalSeconds(summary: MachineUsageSummary) {
  return (
    summary.movingSeconds +
    summary.engineOnSeconds +
    summary.idleSeconds +
    summary.noDataSeconds
  )
}
