'use client'

import * as React from 'react'
import {Popover, PopoverContent, PopoverTrigger} from '@/components/ui/popover'
import {Button} from './ui/button'
import {merge} from '@/lib/utils'
import {CalendarIcon} from 'lucide-react'
import {format, isValid} from 'date-fns'
import {Calendar} from './ui/calendar'
import {DateRange} from 'react-day-picker'

export type DateRangePickerProps = {
  className?: string
  onChange?: (dateRange: DateRange | undefined) => void
  value?: DateRange
  disabled?: boolean
  required?: boolean
  placeholder?: string
  error?: boolean
  errorMessage?: string
  description?: string
  helperText?: string
  format?: string
  name?: string
  fromDate?: Date
  toDate?: Date
  numberOfMonths?: number
  showOutsideDays?: boolean
  fixedWeeks?: boolean
  weekStartsOn?: 0 | 1 | 2 | 3 | 4 | 5 | 6
  onBlur?: () => void
  calendarClassName?: string
}

export default function DateRangePicker({
  className,
  onChange,
  value,
  disabled,
  required,
  placeholder = '选择日期范围',
  format: dateFormat = 'yyyy-MM-dd',
  name,
  fromDate,
  toDate,
  numberOfMonths = 2,
  showOutsideDays = true,
  fixedWeeks = false,
  weekStartsOn = 1,
  onBlur,
  calendarClassName,
}: DateRangePickerProps) {
  const [open, setOpen] = React.useState(false)

  const handleSelectRange = (range: DateRange | undefined) => {
    onChange?.(range)
    if (range?.from && range?.to) {
      setOpen(false)
    }
  }

  // 格式化显示的日期范围
  const displayValue = React.useMemo(() => {
    const formatDate = (date: Date | undefined) => {
      return date && isValid(date) ? format(date, dateFormat) : ''
    }

    if (!value?.from) return placeholder

    if (!value.to) {
      return `${formatDate(value.from)}`
    }

    return `${formatDate(value.from)} ~ ${formatDate(value.to)}`
  }, [value, placeholder, dateFormat])

  const handleOpenChange = (isOpen: boolean) => {
    setOpen(isOpen)
    if (!isOpen) {
      onBlur?.()
    }
  }

  return (
    <Popover open={open} onOpenChange={handleOpenChange}>
      <PopoverTrigger asChild>
        <Button
          theme="outline"
          className={merge(
            'w-full justify-start text-left font-normal h-9',
            !value && 'text-muted-foreground',
            disabled && 'cursor-not-allowed opacity-70',
            className,
          )}
          disabled={disabled}
        >
          <CalendarIcon className="mr-2 h-4 w-4"/>
          <span className={merge('flex-1', !value?.from && 'text-muted-foreground')}>
            {displayValue}
          </span>
        </Button>
      </PopoverTrigger>
      <PopoverContent className="w-auto p-0" align="start">
        <Calendar
          mode="range"
          defaultMonth={value?.from}
          selected={value}
          onSelect={handleSelectRange}
          numberOfMonths={numberOfMonths}
          showOutsideDays={showOutsideDays}
          fixedWeeks={fixedWeeks}
          weekStartsOn={weekStartsOn}
          disabled={
            !!fromDate && !!toDate ? {
              before: fromDate,
              after: toDate,
            } : !!fromDate ? {
              before: fromDate,
            } : !!toDate ? {
              after: toDate,
            } : undefined
          }
          initialFocus
          className={calendarClassName}
        />
      </PopoverContent>
    </Popover>
  )
}
