import * as React from 'react'
import { format } from 'date-fns'
import { CalendarIcon } from 'lucide-react'

import { cn } from '@/lib/utils'
import { Button } from './button'
import { Calendar } from './calendar'
import { Popover, PopoverContent, PopoverTrigger } from './popover'

export interface DatePickerProps {
  value?: Date
  defaultValue?: Date
  onChange?: (date: Date | undefined) => void
  placeholder?: React.ReactNode
  disabled?: boolean
  className?: string
  align?: 'start' | 'center' | 'end'
  formatString?: string
  id?: string
  name?: string
  'aria-label'?: string
}

function DatePicker({
  value,
  defaultValue,
  onChange,
  placeholder = 'Pick a date',
  disabled,
  className,
  align = 'start',
  formatString = 'PPP',
  id,
  name,
  'aria-label': ariaLabel,
}: DatePickerProps) {
  const isControlled = value !== undefined
  const [internal, setInternal] = React.useState<Date | undefined>(defaultValue)
  const [open, setOpen] = React.useState(false)
  const selected = isControlled ? value : internal

  const handleSelect = React.useCallback(
    (next: Date | undefined) => {
      if (!isControlled) setInternal(next)
      onChange?.(next)
      if (next) setOpen(false)
    },
    [isControlled, onChange],
  )

  return (
    <Popover open={open} onOpenChange={setOpen}>
      <PopoverTrigger asChild>
        <Button
          id={id}
          variant="outline"
          disabled={disabled}
          aria-label={ariaLabel ?? (typeof placeholder === 'string' ? placeholder : 'Pick a date')}
          className={cn(
            'w-64 justify-start text-left font-normal rounded-lg active:scale-100',
            !selected && 'text-text-tertiary',
            className,
          )}
          prefixIcon={<CalendarIcon className="size-4 text-text-tertiary" />}
        >
          {selected ? format(selected, formatString) : <span>{placeholder}</span>}
        </Button>
      </PopoverTrigger>
      <PopoverContent className="w-auto p-0" contentPadding="none" align={align}>
        <Calendar
          mode="single"
          selected={selected}
          defaultMonth={selected}
          onSelect={handleSelect}
          autoFocus
        />
        {name ? (
          <input type="hidden" name={name} value={selected ? selected.toISOString() : ''} />
        ) : null}
      </PopoverContent>
    </Popover>
  )
}

export { DatePicker }
