import React, { useEffect, useRef, useState } from "react"
import DatePicker, { DateObject } from "react-multi-date-picker"
import persian from "react-date-object/calendars/persian"
import persian_fa from "react-date-object/locales/persian_fa"
import gregorian from "react-date-object/calendars/gregorian"
import gregorian_en from "react-date-object/locales/gregorian_en"
import "react-multi-date-picker/styles/backgrounds/bg-dark.css"

interface JalaliDatePickerProps {
  value: string | null | undefined;
  onChange: (date: string) => void;
  label?: string;
  disabled?: boolean;
  inputClassName?: string;
  placeholder?: string;
}

export default function JalaliDatePicker({ value, onChange, label, disabled, inputClassName = "", placeholder }: JalaliDatePickerProps) {
  const isFa = document.documentElement.dir === 'rtl'
  const [isDark, setIsDark] = useState(document.documentElement.classList.contains('dark'))
  const containerRef = useRef<HTMLDivElement>(null)
  const [calendarPosition, setCalendarPosition] = useState("bottom-right")

  // Listen for dark mode changes dynamically (optional but good for UX)
  useEffect(() => {
    const observer = new MutationObserver(() => {
      setIsDark(document.documentElement.classList.contains('dark'))
    })
    observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class'] })
    return () => observer.disconnect()
  }, [])

  const handleChange = (date: DateObject | null) => {
    if (!date) {
      onChange("")
    } else {
      // Always output standard Gregorian "YYYY-MM-DD" for backend
      onChange(date.convert(gregorian, gregorian_en).format("YYYY-MM-DD"))
    }
  }

  const updateCalendarPosition = () => {
    const rect = containerRef.current?.getBoundingClientRect()
    if (!rect) return

    const estimatedHeight = 340
    const hasMoreSpaceAbove = rect.top > window.innerHeight - rect.bottom
    const shouldOpenTop = window.innerHeight - rect.bottom < estimatedHeight && hasMoreSpaceAbove
    const horizontal = isFa ? "left" : "right"
    setCalendarPosition(`${shouldOpenTop ? "top" : "bottom"}-${horizontal}`)
  }

  return (
    <div ref={containerRef} className="w-full">
      {label && (
        <label className="text-sm font-medium dark:text-slate-300 mb-1 block">
          {label}
        </label>
      )}
      <DatePicker
        value={value ? new Date(value) : null}
        onChange={handleChange}
        calendar={isFa ? persian : gregorian}
        locale={isFa ? persian_fa : gregorian_en}
        format="YYYY/MM/DD"
        placeholder={placeholder || "YYYY/MM/DD"}
        onOpenPickNewDate={false}
        onOpen={updateCalendarPosition}
        inputClass={`w-full rounded-md border border-slate-300 bg-transparent px-3 py-2 text-sm dark:border-slate-700 dark:text-white focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed ${inputClassName}`}
        containerClassName="w-full"
        className={isDark ? "bg-dark" : ""}
        calendarPosition={calendarPosition}
        fixMainPosition
        disabled={disabled}
      />
    </div>
  )
}
