'use client';

import * as React from 'react';
import { ChevronDown } from 'lucide-react';
import { Button } from './button';
import { Calendar } from './calendar';
import { Popover, PopoverTrigger, PopoverContent } from './popover';

/// 纯日期选择器(shadcn「Date Picker」模式:outline Button + ChevronDown 触发 → Popover + Calendar)。
/// 时间另用 <input type="time">,不在此组件内(对齐 shadcn Date Picker with Time 示例)。
export function DatePicker({
  value,
  onChange,
  placeholder = '选择日期',
  min,
}: {
  value?: Date;
  onChange: (d: Date | undefined) => void;
  placeholder?: string;
  min?: Date;
}) {
  const [open, setOpen] = React.useState(false);
  // 年份下拉范围:当前月 → +2 年(回访不会更远),captionLayout=dropdown 用
  const endMonth = new Date(new Date().getFullYear() + 2, 11);

  return (
    <Popover open={open} onOpenChange={setOpen}>
      <PopoverTrigger asChild>
        <Button variant="outline" className="w-full justify-between font-normal h-9 text-[12.5px]">
          {value ? (
            `${value.getFullYear()}年${value.getMonth() + 1}月${value.getDate()}日`
          ) : (
            <span className="text-slate-400">{placeholder}</span>
          )}
          <ChevronDown className="h-4 w-4 opacity-50" />
        </Button>
      </PopoverTrigger>
      <PopoverContent className="w-auto overflow-hidden p-0" align="start">
        <Calendar
          mode="single"
          selected={value}
          captionLayout="dropdown"
          defaultMonth={value ?? min}
          startMonth={min}
          endMonth={endMonth}
          disabled={min ? { before: min } : undefined}
          onSelect={(d) => {
            onChange(d);
            if (d) setOpen(false);
          }}
        />
      </PopoverContent>
    </Popover>
  );
}
