"use client"
import React from "react"
import { useDateTimeFormatter } from "../../hooks"
import { CalendarToday } from "../../icons"
import { classNames } from "../../utils"
import { Button, ButtonProps } from "../Button"
import { Calendar, CalendarProps } from "../Calendar/Calendar"
import { Popover } from "../Popover"

export type DatePickerProps = CalendarProps & {
  placeholder?: string
  format?: (date: Date | undefined) => string
  size?: ButtonProps["size"]
  error?: boolean
  portal?: boolean
  overrides?: {
    Button?: Partial<ButtonProps>
  }
}

export function DatePicker({
  overrides,
  selected,
  onSelect,
  placeholder = "Select a date",
  format: formatFn,
  size = "md",
  disabled,
  error,
  portal,
  ...props
}: DatePickerProps) {
  const defaultFormat = useDateTimeFormatter()

  const formattedSelected = formatFn
    ? formatFn(selected)
    : defaultFormat(selected, { display: "date-numeric" })

  const disabledButton = typeof disabled === "boolean" && disabled

  return (
    <Popover
      className="min-h-[344px]"
      content={
        <Calendar
          disabled={disabled}
          initialFocus
          selected={selected}
          onSelect={onSelect}
          {...props}
        />
      }
      portal={portal}
    >
      <Button
        className={classNames(
          selected && "font-mono",
          error && "border !border-error",
        )}
        disabled={disabledButton}
        icon={CalendarToday}
        iconSide="right"
        size={size}
        variant="secondary"
        {...overrides?.Button}
      >
        {selected ? formattedSelected : placeholder}
      </Button>
    </Popover>
  )
}
