import { DatePicker } from 'antd'
import type { DatePickerProps } from 'antd'
import type { RangePickerProps } from 'antd/es/date-picker'
import dayjs from 'dayjs'

import {
  ADMIN_DATE_FORMAT,
  ADMIN_DATE_RANGE_PLACEHOLDER,
  ADMIN_DATE_TIME_FORMAT,
  ADMIN_DATE_TIME_RANGE_PLACEHOLDER,
} from '@/lib/dayjs'

type AdminDatePickerProps = DatePickerProps

type AdminRangePickerProps = RangePickerProps

/** 后台日期范围快捷选项：今天 / 昨天 / 近7天 / 近30天 / 本月。 */
function buildAdminDateRangePresets(): NonNullable<RangePickerProps['presets']> {
  const today = dayjs()
  const yesterday = today.subtract(1, 'day')
  return [
    { label: '今天', value: [today.startOf('day'), today.endOf('day')] },
    { label: '昨天', value: [yesterday.startOf('day'), yesterday.endOf('day')] },
    { label: '近7天', value: [today.subtract(6, 'day').startOf('day'), today.endOf('day')] },
    { label: '近30天', value: [today.subtract(29, 'day').startOf('day'), today.endOf('day')] },
    { label: '本月', value: [today.startOf('month'), today.endOf('month')] },
  ]
}

/**
 * 后台统一日期选择：中文 locale（依赖全局 dayjs zh-cn + ConfigProvider zh_CN）。
 */
export function AdminDatePicker({
  format,
  placeholder = '请选择日期',
  ...rest
}: AdminDatePickerProps) {
  const resolvedFormat = format ?? (rest.showTime ? ADMIN_DATE_TIME_FORMAT : ADMIN_DATE_FORMAT)

  return <DatePicker format={resolvedFormat} placeholder={placeholder} {...rest} />
}

/**
 * 后台统一日期范围：默认 YYYY-MM-DD；showTime 时 YYYY-MM-DD HH:mm:ss。
 * 默认附带 今天/昨天/近7天/近30天/本月 快捷选项，传 presets={[]} 可关闭。
 */
export function AdminRangePicker({
  format,
  placeholder,
  presets = buildAdminDateRangePresets(),
  ...rest
}: AdminRangePickerProps) {
  const withTime = Boolean(rest.showTime)
  const resolvedFormat = format ?? (withTime ? ADMIN_DATE_TIME_FORMAT : ADMIN_DATE_FORMAT)
  const resolvedPlaceholder =
    placeholder ?? (withTime ? ADMIN_DATE_TIME_RANGE_PLACEHOLDER : ADMIN_DATE_RANGE_PLACEHOLDER)

  return (
    <DatePicker.RangePicker
      format={resolvedFormat}
      placeholder={resolvedPlaceholder}
      presets={presets}
      {...rest}
    />
  )
}

export default AdminDatePicker
