'use client'

import * as React from 'react'
import { Button } from '@admin/components/ui/button'
import { Calendar } from '@admin/components/ui/calendar'
import { Popover, PopoverContent, PopoverTrigger } from '@admin/components/ui/popover'
import { cn } from '@admin/utils/shared/cn'
import { format } from 'date-fns'
import { CalendarIcon } from 'lucide-react'

interface DatePickerProps {
  value?: string
  onChange?: (value: string) => void
  disabled?: boolean
  placeholder?: string
  className?: string
  startYear?: number
  endYear?: number
}

export function DatePicker({
  value,
  onChange,
  disabled,
  placeholder = 'Pick a date',
  className,
  startYear = 2022,
  endYear = new Date().getFullYear() + 5
}: DatePickerProps) {
  const [date, setDate] = React.useState<Date | undefined>(value ? new Date(value) : undefined)
  const [open, setOpen] = React.useState(false)

  return (
    <Popover open={open} onOpenChange={setOpen}>
      <PopoverTrigger
        render={
          <Button
            variant="outline"
            size="lg"
            className={cn(
              'w-full justify-start pl-3! text-left font-normal',
              { 'text-muted-foreground': !date },
              className
            )}
            disabled={disabled}
          />
        }
      >
        <CalendarIcon className="size-4" />
        {date ? format(date, 'PPP') : <span>{placeholder}</span>}
      </PopoverTrigger>
      <PopoverContent className="w-auto overflow-hidden p-0" align="start">
        <Calendar
          mode="single"
          selected={date}
          captionLayout="dropdown"
          startMonth={new Date(startYear, 0)}
          endMonth={new Date(endYear, 11)}
          onSelect={(_date) => {
            setDate(_date)
            if (onChange) {
              onChange(_date ? format(_date, 'yyyy-MM-dd') : '')
            }
            setOpen(false)
          }}
        />
      </PopoverContent>
    </Popover>
  )
}
