"use client"
import { da, de, fi, nb, sv } from "date-fns/locale"
import { useState } from "react"
import { type DateRange, DayPicker } from "react-day-picker"

import { Lang } from "@/constants/languages"
import { dt } from "@/lib/dt"

import useLang from "@/hooks/useLang"

import classNames from "react-day-picker/style.module.css"

const locales = {
  [Lang.da]: da,
  [Lang.de]: de,
  [Lang.fi]: fi,
  [Lang.no]: nb,
  [Lang.sv]: sv,
}

export interface DatePickerProps {
  handleOnSelect: (selected: DateRange) => void
  initialSelected?: DateRange
}

export default function DatePicker({
  handleOnSelect,
  initialSelected = {
    from: undefined,
    to: undefined,
  },
}: DatePickerProps) {
  const lang = useLang()
  const [selectedDate, setSelectedDate] = useState<DateRange>(initialSelected)

  function handleSelectDate(selected: DateRange) {
    handleOnSelect(selected)
    setSelectedDate(selected)
  }

  /** English is default language and doesn't need to be imported */
  const locale = lang === Lang.en ? undefined : locales[lang]

  const currentDate = dt().toDate()
  const startOfMonth = dt(currentDate).set("date", 1).toDate()
  const yesterday = dt(currentDate).subtract(1, "day").toDate()
  return (
    <DayPicker
      classNames={classNames}
      disabled={{ from: startOfMonth, to: yesterday }}
      excludeDisabled
      locale={locale}
      mode="range"
      onSelect={handleSelectDate}
      pagedNavigation
      required
      selected={selectedDate}
      showWeekNumber
      startMonth={currentDate}
    />
  )
}
