'use client'

import * as React from 'react'
import { CustomSelect } from './select'
import { ClockIcon } from 'lucide-react'

export interface TimeInputProps {
  value?: Date
  onChange: (date: Date) => void
  label?: string
  placeholder?: string
  className?: string
  hasError?: boolean
  errorMessage?: string
  selectedDate?: Date 
}

const roundToNext30Min = (date: Date) => {
  const newDate = new Date(date)
  const minutes = newDate.getMinutes()
  const roundedMinutes = minutes < 30 ? 30 : 0
  if (roundedMinutes === 0) {
    newDate.setHours(newDate.getHours() + 1)
  }
  newDate.setMinutes(roundedMinutes, 0, 0)
  return newDate
}


const timeOptions = Array.from({ length: (21 - 6) * 2 + 1 }, (_, idx) => {
  const totalMinutes = (6 * 60) + idx * 30 // стартуем с 6:00
  const hours24 = Math.floor(totalMinutes / 60)
  const minutes = totalMinutes % 60

  const period = hours24 < 12 ? 'AM' : 'PM'
  const hours12 = hours24 % 12 === 0 ? 12 : hours24 % 12

  const pad = (n: number) => String(n).padStart(2, '0')
  const label = `${hours12}:${pad(minutes)} ${period}`
  const value = `${pad(hours24)}:${pad(minutes)}`

  return { value, label }
})


export function TimeInput({
  value,
  onChange,
  label,
  placeholder = 'Select time',
  className,
  hasError,
  errorMessage,
  selectedDate,
}: TimeInputProps) {
  const today = new Date()
  const currentHour = today.getHours()
  const currentMinute = today.getMinutes()

  // Проверяем, является ли выбранная дата сегодняшней
  // const isToday = selectedDate ? selectedDate.getDate() === today.getDate() : false

  const isToday =
    selectedDate &&
    selectedDate.getDate() === today.getDate() &&
    selectedDate.getMonth() === today.getMonth() &&
    selectedDate.getFullYear() === today.getFullYear()
  
   // первый раз устанавливаем roundedNow
   React.useEffect(() => {
    if (!value && isToday) {
      const baseDate = selectedDate ?? today
      const rounded = roundToNext30Min(baseDate)
      onChange(rounded)
    }
  }, [value, isToday, onChange, today, selectedDate])
  
  
  // React.useEffect(() => {
  //   if (!value && isToday) {
  //     const roundedNow = roundToNext30Min(today)
  //     console.log('roundedNow',roundedNow)
  //     onChange(roundedNow)
  //   }
  // }, [])

  // const optionsWithDisabled = timeOptions.filter(option => {
  //   const [hours, minutes] = option.value.split(':').map(Number)
  //   const isDisabled = isToday &&
  //     ((hours < currentHour) ||
  //      (hours === currentHour && minutes < currentMinute))
      
  //   return !isDisabled
  // })
  
  // фильтруем опции: disable прошедшее время, если выбран сегодня
  const optionsWithDisabled = React.useMemo(() => {
    if (!isToday) return timeOptions
    return timeOptions.filter((option) => {
      const [h, m] = option.value.split(':').map(Number)
      const nowH = today.getHours()
      const nowM = today.getMinutes()
      // если время прошло, убираем из списка
      return h > nowH || (h === nowH && m >= nowM)
    })
  }, [isToday, today])

  // const initialValue = isToday && !value ? 
  // roundToNext30Min(today) :
  // value

  // const selectedValue =
  // initialValue instanceof Date
  //     ? `${String(initialValue.getHours()).padStart(2, '0')}:${String(initialValue.getMinutes()).padStart(2, '0')}`
  //     : undefined
  
   // selected value для select
   const selectedValue =
   value instanceof Date
     ? `${String(value.getHours()).padStart(2, '0')}:${String(
         value.getMinutes()
       ).padStart(2, '0')}`
     : undefined

  return (
    <CustomSelect
      options={optionsWithDisabled}
      placeholder={placeholder}
      label={label}
      className={className}
      value={selectedValue}
      iconLeft={<ClockIcon className="size-5 stroke-grey-200" />}
      // onValueChange={(val) => {
      //   const [h, m] = val.split(':').map(Number)
      //   const date = value ? new Date(value) : new Date()
      //   date.setHours(h, m, 0, 0)
      //   onChange(date)
      // }}
      onValueChange={(val) => {
        const [h, m] = val.split(':').map(Number)
        // берем дату из selectedDate, если она есть, иначе fallback на value или сегодня
        const baseDate = selectedDate ?? value ?? new Date()
        const date = new Date(baseDate)
        date.setHours(h, m, 0, 0)
        onChange(date)
      }}
      
      hasError={hasError}
      errorMessage={errorMessage}
    />
  )
}
