"use client"

import * as React from "react"
import { Calendar as CalendarIcon } from "lucide-react"
import dayjs, { type Dayjs } from "dayjs"

import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { Calendar } from "@/components/ui/calendar"
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"

interface DatePickerProps {
  className?: string
  value?: string | Dayjs
  onChange?: (date: Dayjs) => void
}

export function DatePicker({ className, value, onChange }: DatePickerProps) {
  const toDate = (val: string | Dayjs | undefined): Date | undefined => {
    if (!val) return undefined
    return new Date(typeof val === 'string' ? val : val.toISOString())
  }

  const date = toDate(value)

  const handleSelect = (selectedDate: Date | undefined) => {
    if (selectedDate && onChange) {
      onChange(dayjs(selectedDate))
    }
  }

  return (
    <Popover>
      <PopoverTrigger asChild>
        <Button
          variant={"outline"}
          className={cn(
            "w-full justify-start text-left font-normal",
            !date && "text-muted-foreground",
            className
          )}
        >
          <CalendarIcon className="mr-2 h-4 w-4" />
          {date ? dayjs(date).format("YYYY-MM-DD") : <span>选择日期</span>}
        </Button>
      </PopoverTrigger>
      <PopoverContent className="w-auto p-0" align="start">
        <Calendar
          mode="single"
          selected={date}
          onSelect={handleSelect}
        />
      </PopoverContent>
    </Popover>
  )
}
