import { ChevronLeft, ChevronRight, Calendar } from 'lucide-react'
import { useState, useCallback, useEffect } from 'react'

interface MonthPickerProps {
  month: string
  onChange: (month: string) => void
  rangeMode?: 'month' | 'quarter' | 'halfyear' | 'year' | 'custom'
  onRangeModeChange?: (mode: 'month' | 'quarter' | 'halfyear' | 'year' | 'custom') => void
}

const RANGE_MODES: { value: 'month' | 'quarter' | 'halfyear' | 'year' | 'custom'; label: string }[] = [
  { value: 'month', label: '月度' },
  { value: 'quarter', label: '季度' },
  { value: 'halfyear', label: '半年' },
  { value: 'year', label: '全年' },
]

export function MonthPicker({ month, onChange, rangeMode = 'month', onRangeModeChange }: MonthPickerProps) {
  const [showPicker, setShowPicker] = useState(false)

  const displayMonth = month.length === 10 ? month.substring(0, 7) : month

  const prevMonth = useCallback(() => {
    const [y, m] = displayMonth.split('-').map(Number)
    const d = new Date(y, m - 2, 1)
    onChange(`${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`)
  }, [displayMonth, onChange])

  const nextMonth = useCallback(() => {
    const [y, m] = displayMonth.split('-').map(Number)
    const d = new Date(y, m, 1)
    onChange(`${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`)
  }, [displayMonth, onChange])

  useEffect(() => {
    const handler = () => setShowPicker(false)
    if (showPicker) {
      window.addEventListener('click', handler)
      return () => window.removeEventListener('click', handler)
    }
  }, [showPicker])

  return (
    <div className="flex items-center gap-2">
      <div className="flex items-center gap-1 rounded-md border bg-card px-1 py-0.5">
        <button
          onClick={prevMonth}
          className="rounded p-1 hover:bg-muted"
          title="上月"
        >
          <ChevronLeft size={16} />
        </button>
        <div className="relative">
          <button
            onClick={(e) => { e.stopPropagation(); setShowPicker(!showPicker) }}
            className="flex items-center gap-1 px-2 py-1 text-sm font-medium hover:bg-muted rounded"
          >
            <Calendar size={14} />
            {displayMonth}
          </button>
          {showPicker && (
            <div
              className="absolute top-full left-0 z-50 mt-1 rounded-md border bg-card p-3 shadow-lg"
              onClick={(e) => e.stopPropagation()}
            >
              <input
                type="month"
                value={displayMonth}
                onChange={(e) => {
                  onChange(e.target.value)
                  setShowPicker(false)
                }}
                className="rounded border px-2 py-1 text-sm"
              />
            </div>
          )}
        </div>
        <button
          onClick={nextMonth}
          className="rounded p-1 hover:bg-muted"
          title="下月"
        >
          <ChevronRight size={16} />
        </button>
      </div>

      {onRangeModeChange && (
        <div className="flex items-center gap-1 rounded-md border bg-card px-1 py-0.5">
          {RANGE_MODES.map((m) => (
            <button
              key={m.value}
              onClick={() => onRangeModeChange(m.value)}
              className={`rounded px-2 py-1 text-xs font-medium transition-colors ${
                rangeMode === m.value
                  ? 'bg-primary text-primary-foreground'
                  : 'hover:bg-muted'
              }`}
            >
              {m.label}
            </button>
          ))}
        </div>
      )}
    </div>
  )
}
