import { ActionIcon, Button, Group, TextInput, Tooltip } from '@pikku/mantine/core'
import { m } from '@/i18n/messages'
import { useLocale } from '@/i18n/config'

export const todayIso = () => new Date().toISOString().slice(0, 10)

export const shiftDate = (iso: string, days: number) => {
  const d = new Date(iso + 'T00:00:00Z')
  d.setUTCDate(d.getUTCDate() + days)
  return d.toISOString().slice(0, 10)
}

export function DateBar({
  date,
  onChange,
}: {
  date: string
  onChange: (next: string) => void
}) {
  useLocale()
  const isToday = date === todayIso()
  return (
    <Group gap="xs" wrap="nowrap" align="center" data-testid="date-bar">
      <Tooltip label={m.common_pages_staff_prev_day()}>
        <ActionIcon
          variant="default"
          size="lg"
          onClick={() => onChange(shiftDate(date, -1))}
          aria-label={m.common_pages_staff_prev_day()}
          data-testid="date-bar-prev"
        >
          ‹
        </ActionIcon>
      </Tooltip>
      <TextInput
        type="date"
        size="sm"
        value={date}
        onChange={(e) => {
          const v = e.currentTarget.value
          if (v) onChange(v)
        }}
        data-testid="date-bar-input"
        styles={{ input: { minWidth: 160 } }}
      />
      <Tooltip label={m.common_pages_staff_next_day()}>
        <ActionIcon
          variant="default"
          size="lg"
          onClick={() => onChange(shiftDate(date, 1))}
          aria-label={m.common_pages_staff_next_day()}
          data-testid="date-bar-next"
        >
          ›
        </ActionIcon>
      </Tooltip>
      <Button
        size="xs"
        variant={isToday ? 'filled' : 'light'}
        color="plum"
        onClick={() => onChange(todayIso())}
        disabled={isToday}
        data-testid="date-bar-today"
      >
        {m.common_pages_staff_today()}
      </Button>
    </Group>
  )
}
