/**
 * 月份选择器组件
 * 使用小程序 Picker 组件选择年月
 */
import React from 'react'
import { View, Text, Picker } from '@tarojs/components'
import { MonthSelectorProps } from '../types/attendance'

export const MonthSelector: React.FC<MonthSelectorProps> = ({
  currentMonth,
  onPreviousMonth,
  onNextMonth,
  onMonthChange
}) => {
  // 生成最近3年的月份选项
  const currentYear = new Date().getFullYear()
  const yearOptions = Array.from({ length: 3 }, (_, i) => currentYear - 1 + i)
  const monthOptions = Array.from({ length: 12 }, (_, i) => i + 1)

  const yearRange = [
    yearOptions.map((y) => `${y}年`),
    monthOptions.map((m) => `${m}月`)
  ]

  // 解析当前年月
  const parseCurrentMonth = () => {
    const match = currentMonth.match(/(\d+)年(\d+)月/)
    if (match) {
      return { year: parseInt(match[1]), month: parseInt(match[2]) }
    }
    return { year: currentYear, month: new Date().getMonth() + 1 }
  }

  const { year: selectedYear, month: selectedMonth } = parseCurrentMonth()

  // 计算默认选中的索引
  const defaultValue = [
    yearOptions.indexOf(selectedYear),
    selectedMonth - 1
  ]

  // 处理 Picker 选择变化
  const handlePickerChange = (e: any) => {
    if (!onMonthChange) return

    const [yearIndex, monthIndex] = e.detail.value
    const newYear = yearOptions[yearIndex]
    const newMonth = monthOptions[monthIndex]
    onMonthChange(newYear, newMonth)
  }

  return (
    <View className="flex justify-between items-center mb-4 px-4">
      <Text className="font-semibold text-gray-700 text-base">考勤记录</Text>
      <View className="flex items-center bg-gray-100 rounded-lg">
        {/* 左箭头图标 */}
        <View
          className="i-heroicons-chevron-left-20-solid w-5 h-5 text-gray-500 mx-2"
          onClick={onPreviousMonth}
        />
        {/* 月份选择器 */}
        <Picker
          mode="multiSelector"
          range={yearRange}
          value={defaultValue}
          onChange={handlePickerChange}
        >
          <View className="px-2 py-1">
            <Text className="text-sm text-gray-700">{currentMonth}</Text>
          </View>
        </Picker>
        {/* 右箭头图标 */}
        <View
          className="i-heroicons-chevron-right-20-solid w-5 h-5 text-gray-500 mx-2"
          onClick={onNextMonth}
        />
      </View>
    </View>
  )
}
