import MultiDatePicker from 'react-multi-date-picker'
import TimePicker from 'react-multi-date-picker/plugins/time_picker'
import persian from 'react-date-object/calendars/persian'
import persian_fa from 'react-date-object/locales/persian_fa'
import { DateObject } from 'react-multi-date-picker'
import type { Value } from 'react-multi-date-picker'

interface DateTimePickerProps {
  value?: string // YYYY-MM-DD HH:mm:ss or YYYY-MM-DDTHH:mm:ss format (Gregorian)
  onChange: (value: string) => void
  placeholder?: string
  className?: string
  disabled?: boolean
  required?: boolean
}

export const DateTimePicker = ({
  value,
  onChange,
  placeholder = 'تاریخ و ساعت را انتخاب کنید',
  className = '',
  disabled = false,
  required = false,
}: DateTimePickerProps) => {
  const handleChange = (date: Value) => {
    if (!date) {
      onChange('')
      return
    }

    // Convert to DateObject if it's an array (take first date)
    const dateObj = Array.isArray(date) ? date[0] : date

    if (!dateObj || typeof dateObj === 'string') {
      onChange('')
      return
    }

    // Convert Persian DateObject to native Date, then format as YYYY-MM-DD HH:mm:ss
    const persianDate = dateObj as DateObject
    const nativeDate = persianDate.toDate()
    
    const year = nativeDate.getFullYear()
    const month = String(nativeDate.getMonth() + 1).padStart(2, '0')
    const day = String(nativeDate.getDate()).padStart(2, '0')
    const hours = String(nativeDate.getHours()).padStart(2, '0')
    const minutes = String(nativeDate.getMinutes()).padStart(2, '0')
    const seconds = String(nativeDate.getSeconds()).padStart(2, '0')
    const formattedDateTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`

    onChange(formattedDateTime)
  }

  // Convert Gregorian datetime to Persian DateObject for display
  const getPersianDateTime = (): DateObject | undefined => {
    if (!value) return undefined

    try {
      // Handle both "YYYY-MM-DD HH:mm:ss" and "YYYY-MM-DDTHH:mm:ss" formats
      const normalizedValue = value.replace('T', ' ')
      const [datePart, timePart] = normalizedValue.split(' ')
      const [year, month, day] = datePart.split('-').map(Number)
      
      let hours = 0, minutes = 0, seconds = 0
      if (timePart) {
        const timeParts = timePart.split(':').map(Number)
        hours = timeParts[0] || 0
        minutes = timeParts[1] || 0
        seconds = timeParts[2] || 0
      }
      
      const gregorianDate = new Date(year, month - 1, day, hours, minutes, seconds)
      return new DateObject({
        date: gregorianDate,
        calendar: persian,
        locale: persian_fa,
      })
    } catch {
      return undefined
    }
  }

  return (
    <MultiDatePicker
      value={getPersianDateTime()}
      onChange={handleChange}
      calendar={persian}
      locale={persian_fa}
      calendarPosition="bottom-right"
      placeholder={placeholder}
      disabled={disabled}
      required={required}
      format="YYYY/MM/DD HH:mm"
      plugins={[
        <TimePicker 
          key="time"
          position="bottom"
          hideSeconds
        />
      ]}
      inputClass={`h-11 w-full rounded-lg border border-gray-300 bg-transparent px-4 py-2.5 text-sm shadow-theme-xs placeholder:text-gray-400 focus:border-brand-300 focus:outline-hidden focus:ring-3 focus:ring-brand-500/20 disabled:cursor-not-allowed disabled:opacity-50 dark:border-gray-700 dark:bg-gray-900 dark:text-white/90 ${className}`}
      containerClassName="w-full"
    />
  )
}
