import MultiDatePicker from 'react-multi-date-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 DatePickerProps {
  value?: string // YYYY-MM-DD format (Gregorian)
  onChange: (value: string) => void
  placeholder?: string
  className?: string
  disabled?: boolean
  required?: boolean
}

export const DatePicker = ({
  value,
  onChange,
  placeholder = 'تاریخ را انتخاب کنید',
  className = '',
  disabled = false,
  required = false,
}: DatePickerProps) => {
  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
    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 formattedDate = `${year}-${month}-${day}`

    onChange(formattedDate)
  }

  // Convert Gregorian date (YYYY-MM-DD) to Persian DateObject for display
  const getPersianDate = (): DateObject | undefined => {
    if (!value) return undefined

    try {
      const [year, month, day] = value.split('-').map(Number)
      const gregorianDate = new Date(year, month - 1, day)
      return new DateObject({
        date: gregorianDate,
        calendar: persian,
        locale: persian_fa,
      })
    } catch {
      return undefined
    }
  }

  return (
    <MultiDatePicker
      value={getPersianDate()}
      onChange={handleChange}
      calendar={persian}
      locale={persian_fa}
      calendarPosition="bottom-right"
      placeholder={placeholder}
      disabled={disabled}
      required={required}
      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"
      format="YYYY/MM/DD"
    />
  )
}
