import React, { useState, useEffect } from 'react'
import { View, Text, } from '@tarojs/components'
import { getDate, getTime, getDateStr, getEndTime } from '@/utils/timeUtils'
import { DialogCalendarCard } from '@/components/index'
import './TimeSelector.scss'
import dayjs from 'dayjs'

// 安全地解析日期字符串，兼容 iOS
const parseDate = (dateStr: string): Date => {
  if (!dateStr) return new Date();
  // 将 "yyyy-MM-dd HH:mm:ss" 转换为 "yyyy-MM-ddTHH:mm:ss"
  const isoStr = dateStr.replace(/^(\d{4}-\d{2}-\d{2})\s(\d{2}:\d{2}(?::\d{2})?)$/, '$1T$2');
  return new Date(isoStr);
};

export interface TimeRange {
  start_time: string
  end_time: string
}

interface TimeSelectorProps {
  value: TimeRange
  onChange: (timeRange: TimeRange) => void
}

const TimeSelector: React.FC<TimeSelectorProps> = ({ 
  value = {
    start_time: '',
    end_time: ''
  }, 
  onChange
}) => {
  // 格式化日期显示
  const [visible, setVisible] = useState(false)
  const [currentTimeValue, setCurrentTimeValue] = useState<Date>(new Date())
  const [currentTimeType, setCurrentTimeType] = useState<'start' | 'end'>('start')
  const [showEndTime, setShowEndTime] = useState(false)
  const handleConfirm = (date: Date) => {
    console.log('选择的日期:', date)
    const start_time = currentTimeType === 'start' ? getDateStr(date) : value.start_time;
    const end_time = currentTimeType === 'end' ? getDateStr(date) : value.end_time;
    const isLater = dayjs(start_time).isAfter(dayjs(end_time));
    if (isLater) {
      if (onChange) onChange({start_time, end_time: getEndTime(start_time)})
      return
    }
    if (onChange) onChange({start_time, end_time})
  }
  const openPicker = (type: 'start' | 'end') => {
    setCurrentTimeValue(type === 'start' ? parseDate(value.start_time) : parseDate(value.end_time))
    setCurrentTimeType(type)
    setVisible(true)
  }

  useEffect(() => {
    if (value.start_time && value.end_time) {
      const start_time = dayjs(value.start_time).format('YYYY-MM-DD')
      const end_time = dayjs(value.end_time).format('YYYY-MM-DD')
      if (start_time === end_time) {
        setShowEndTime(false)
      } else {
        setShowEndTime(true)
      } 
    }
  }, [value])
  return (
    <View className='time-selector'>
      <View className='time-section'>
        {/* 开始时间 */}
        <View className='time-item'>
          <View className='time-label'>
            <View className='dot'></View>
          </View>
          <View className='time-content' onClick={() => openPicker('start')}>
            <Text className='time-label'>开始时间</Text>
            <view className='time-text-wrapper'>
              {value.start_time && (<>
                <Text className='time-text'>{getDate(value.start_time)}</Text>
              <Text className='time-text time-am'>{getTime(value.start_time)}</Text>
              </>)}
              {!value.start_time && (<Text className='time-text'>请选择开始时间</Text>)}
            </view>
          </View>
        </View>

        {/* 结束时间 */}
        <View className='time-item'>
          <View className='time-label'>
            <View className='dot hollow'></View>
          </View>
          <View className='time-content' onClick={() => openPicker('end')}>
            <Text className='time-label'>结束时间</Text>
            <view className='time-text-wrapper'>
              {value.end_time && (<>{showEndTime && (<Text className='time-text'>{getDate(value.end_time)}</Text>)}
              <Text className='time-text time-am'>{getTime(value.end_time)}</Text></>)}
              {!value.end_time && (<Text className='time-text'>请选择结束时间</Text>)}
            </view>
          </View>
        </View>
      </View>
      {
       visible && <DialogCalendarCard
              visible={visible}
              value={currentTimeValue}
              onChange={handleConfirm}
              onClose={() => setVisible(false)}
      />
      }
    </View>
  )
}

export default TimeSelector
