"use client"

import * as React from "react"
import { format, parseISO } from "date-fns"
import { CalendarIcon } from "lucide-react"

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 {
  value?: string | Date
  onChange?: (date?: string) => void
  placeholder?: string
  className?: string
  triggerClassName?: string
  disabled?: boolean
  calendarProps?: React.ComponentProps<typeof Calendar>
}

export function DatePicker({
  value,
  onChange,
  placeholder = "Pick date",
  className,
  triggerClassName,
  disabled,
  calendarProps,
}: DatePickerProps) {
  const dateValue = React.useMemo(() => {
    if (!value) return undefined
    if (value instanceof Date) return value
    if (typeof value !== "string") return undefined
    
    try {
      // Handle "YYYY-MM-DD" or ISO strings
      const parsed = parseISO(value)
      return isNaN(parsed.getTime()) ? undefined : parsed
    } catch {
      return undefined
    }
  }, [value])

  return (
    <div className={cn("grid gap-2", className)}>
      <Popover>
        <PopoverTrigger asChild>
          <Button
            variant={"outline"}
            type="button"
            disabled={disabled}
            className={cn(
              "w-full justify-start text-left font-normal",
              !dateValue && "text-muted-foreground",
              triggerClassName
            )}
          >
            <CalendarIcon className="mr-2 h-4 w-4 shrink-0" />
            {dateValue ? format(dateValue, "PPP") : <span>{placeholder}</span>}
          </Button>
        </PopoverTrigger>
        <PopoverContent className="w-auto p-0" align="start">
          <Calendar
            {...calendarProps}
            mode="single"
            selected={dateValue}
            onSelect={(d) => {
               if (onChange) {
                 // Use local date formatting to avoid timezone shift issues
                 onChange(d ? format(d, "yyyy-MM-dd") : undefined)
               }
            }}
            initialFocus
          />
        </PopoverContent>
      </Popover>
    </div>
  )
}
