import type {FunctionComponent, InputHTMLAttributes} from 'react'
import {useState} from 'react'
import {CalendarIcon} from 'lucide-react'
import {Popover, PopoverContent, PopoverTrigger} from '@/components/ui/popover'
import {Button} from '@/components/ui/button'
import {format} from 'date-fns'
import {Calendar} from '@/components/ui/calendar'
import {cn} from '@/lib/utils'

interface DatePickerProps extends Omit<InputHTMLAttributes<HTMLInputElement>, 'defaultValue'> {
  onDateChange?: (newDate: Date | undefined) => void
  defaultValue?: Date
}

const DatePicker: FunctionComponent<DatePickerProps> = ({onDateChange, defaultValue, ...inputProps}) => {
  const [date, setDate] = useState<Date | undefined>(defaultValue)

  return (
    <>
      <input type="hidden" value={(date ?? new Date()).toISOString()} {...inputProps} onChange={() => {}} />
      <Popover>
        <PopoverTrigger asChild>
          <Button
            variant="outline"
            className={cn('w-full justify-start text-left font-normal', !date && 'text-muted-foreground')}>
            <CalendarIcon className="mr-2 h-4 w-4" />
            {date ? format(date, 'PPP') : <span>Pick a date</span>}
          </Button>
        </PopoverTrigger>
        <PopoverContent className="w-auto p-0">
          <Calendar
            mode="single"
            selected={date}
            onSelect={newDate => {
              setDate(newDate)
              onDateChange?.(newDate)
            }}
            autoFocus
          />
        </PopoverContent>
      </Popover>
    </>
  )
}

export default DatePicker
