import React, { useState, useEffect, useRef } from 'react'
import { Calendar, ChevronLeft, ChevronRight } from 'lucide-react'
import { isSameDay, isAfter, isBefore, format } from 'date-fns'
import { getKualaLumpurDate, isTodayInKualaLumpur } from '@/lib/utils/date'
import { TZDate } from '@date-fns/tz'
import { ASIA_KUALA_LUMPUR_TIMEZONE } from '@/lib/constants/date'

interface DatePickerProps {
  initialDate?: Date
  minDate?: Date
  maxDate?: Date
  disabled?: boolean
  onChange?: (date: Date, formattedDate: string) => void
}

type ViewMode = 'days' | 'months' | 'years'

const months: string[] = [
  'January',
  'February',
  'March',
  'April',
  'May',
  'June',
  'July',
  'August',
  'September',
  'October',
  'November',
  'December',
]

const weekDays: string[] = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']

const DatePicker: React.FC<DatePickerProps> = ({
  initialDate = new TZDate(new Date(), ASIA_KUALA_LUMPUR_TIMEZONE),
  minDate,
  maxDate,
  disabled,
  onChange,
}) => {
  const [selectedDate, setSelectedDate] = useState<Date>(initialDate)
  const [currentMonth, setCurrentMonth] = useState<Date>(initialDate)

  // View States
  const [isOpen, setIsOpen] = useState<boolean>(false)
  const [viewMode, setViewMode] = useState<ViewMode>('days')
  const datePickerRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    setSelectedDate(initialDate)
  }, [initialDate])

  // Format date as "d F Y" (e.g., "15 February 2024")
  const formatDisplayDate = (date: Date): string => {
    const day = date.getDate()
    const month = months[date.getMonth()]
    const year = date.getFullYear()
    return `${day} ${month} ${year}`
  }

  // Format date as "YYYY-MM-DD"
  const formatSaveDate = (date: Date): string => {
    return format(date, 'yyyy-MM-dd')
  }

  // Generate days for the current month
  const getDaysInMonth = (): (Date | null)[] => {
    const year = currentMonth.getFullYear()
    const month = currentMonth.getMonth()

    const firstDay = new TZDate(
      year,
      month,
      1,
      0,
      0,
      0,
      0,
      ASIA_KUALA_LUMPUR_TIMEZONE,
    )
    const lastDay = new TZDate(
      year,
      month + 1,
      0,
      0,
      0,
      0,
      0,
      ASIA_KUALA_LUMPUR_TIMEZONE,
    )

    const daysInMonth = lastDay.getDate()
    const startingDay = firstDay.getDay()

    const days: (Date | null)[] = []

    // Add empty cells for days before the first of the month
    for (let i = 0; i < startingDay; i++) {
      days.push(null)
    }

    // Add the actual days
    for (let i = 1; i <= daysInMonth; i++) {
      days.push(
        new TZDate(year, month, i, 0, 0, 0, 0, ASIA_KUALA_LUMPUR_TIMEZONE),
      )
    }

    return days
  }

  const handleDateSelect = (date: Date): void => {
    setSelectedDate(date)
    onChange?.(date, formatSaveDate(date))
    setIsOpen(false)
  }

  const handleMonthSelect = (monthIndex: number): void => {
    setCurrentMonth(
      new TZDate(
        currentMonth.getFullYear(),
        monthIndex,
        1,
        0,
        0,
        0,
        0,
        ASIA_KUALA_LUMPUR_TIMEZONE,
      ),
    )
    setViewMode('days')
  }

  const handleYearSelect = (year: number): void => {
    setCurrentMonth(
      new TZDate(
        year,
        currentMonth.getMonth(),
        1,
        0,
        0,
        0,
        0,
        ASIA_KUALA_LUMPUR_TIMEZONE,
      ),
    )
    setViewMode('months')
  }

  const isDateInRange = (date: Date): boolean => {
    if (!date) return false

    const isAfterMinDate = minDate
      ? isAfter(date, minDate) || isSameDay(date, minDate)
      : true
    const isBeforeMaxDate = maxDate
      ? isBefore(date, maxDate) || isSameDay(date, maxDate)
      : true

    return isAfterMinDate && isBeforeMaxDate
  }

  const isToday = (date: Date | null): boolean => {
    if (!date) return false
    return isTodayInKualaLumpur(date)
  }

  const isSelected = (date: Date | null): boolean => {
    if (!date) return false

    return (
      date.getDate() === selectedDate.getDate() &&
      date.getMonth() === selectedDate.getMonth() &&
      date.getFullYear() === selectedDate.getFullYear()
    )
  }

  const isCurrentMonth = (monthIndex: number): boolean => {
    const today = getKualaLumpurDate()

    return (
      monthIndex === today.getMonth() &&
      currentMonth.getFullYear() === today.getFullYear()
    )
  }

  const isSelectedMonth = (monthIndex: number): boolean => {
    return (
      monthIndex === selectedDate.getMonth() &&
      currentMonth.getFullYear() === selectedDate.getFullYear()
    )
  }

  // Handle click outside to close dropdowns
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent): void => {
      if (
        datePickerRef.current &&
        !datePickerRef.current.contains(event.target as Node)
      ) {
        setIsOpen(false)
      }
    }

    document.addEventListener('mousedown', handleClickOutside)
    return () => document.removeEventListener('mousedown', handleClickOutside)
  }, [])

  const renderHeader = () => {
    let title: string
    let decade: number
    let prevHandler: () => void
    let nextHandler: () => void

    switch (viewMode) {
      case 'months':
        title = currentMonth.getFullYear().toString()
        prevHandler = () =>
          setCurrentMonth(
            new TZDate(
              currentMonth.getFullYear() - 1,
              currentMonth.getMonth(),
              1,
              0,
              0,
              0,
              0,
              ASIA_KUALA_LUMPUR_TIMEZONE,
            ),
          )
        nextHandler = () =>
          setCurrentMonth(
            new TZDate(
              currentMonth.getFullYear() + 1,
              currentMonth.getMonth(),
              1,
              0,
              0,
              0,
              0,
              ASIA_KUALA_LUMPUR_TIMEZONE,
            ),
          )
        break
      case 'years':
        decade = Math.floor(currentMonth.getFullYear() / 10) * 10
        title = `${decade} - ${decade + 9}`
        prevHandler = () =>
          setCurrentMonth(
            new TZDate(
              currentMonth.getFullYear() - 10,
              currentMonth.getMonth(),
              1,
              0,
              0,
              0,
              0,
              ASIA_KUALA_LUMPUR_TIMEZONE,
            ),
          )
        nextHandler = () =>
          setCurrentMonth(
            new TZDate(
              currentMonth.getFullYear() + 10,
              currentMonth.getMonth(),
              1,
              0,
              0,
              0,
              0,
              ASIA_KUALA_LUMPUR_TIMEZONE,
            ),
          )
        break
      default:
        title = `${months[currentMonth.getMonth()]} ${currentMonth.getFullYear()}`
        prevHandler = () =>
          setCurrentMonth(
            new TZDate(
              currentMonth.getFullYear(),
              currentMonth.getMonth() - 1,
              1,
              0,
              0,
              0,
              0,
              ASIA_KUALA_LUMPUR_TIMEZONE,
            ),
          )
        nextHandler = () =>
          setCurrentMonth(
            new TZDate(
              currentMonth.getFullYear(),
              currentMonth.getMonth() + 1,
              1,
              0,
              0,
              0,
              0,
              ASIA_KUALA_LUMPUR_TIMEZONE,
            ),
          )
    }

    return (
      <div className="flex items-center justify-between px-4 py-3 border-b border-gray-500 bg-gray-50">
        <button
          type="button"
          onClick={prevHandler}
          className="p-1.5 rounded-full hover:bg-white hover:shadow-sm transition-all duration-200 active:scale-95 cursor-pointer"
          aria-label="Previous"
        >
          <ChevronLeft className="w-4 h-4 text-gray-600" />
        </button>
        <button
          type="button"
          onClick={() => setViewMode(viewMode === 'days' ? 'months' : 'years')}
          className="px-4 py-1.5 font-semibold text-gray-700 rounded-full hover:bg-white hover:shadow-sm transition-all duration-200 cursor-pointer"
        >
          {title}
        </button>
        <button
          type="button"
          onClick={nextHandler}
          className="p-1.5 rounded-full hover:bg-white hover:shadow-sm transition-all duration-200 active:scale-95 cursor-pointer"
          aria-label="Next"
        >
          <ChevronRight className="w-4 h-4 text-gray-600" />
        </button>
      </div>
    )
  }

  const renderMonthsView = () => (
    <div className="grid grid-cols-3 gap-2 p-4">
      {months.map((month, index) => (
        <div
          key={month}
          className={`
            py-3 text-center cursor-pointer text-sm rounded-lg
            transition-all duration-200
            ${
              isCurrentMonth(index)
                ? 'border border-blue-500 text-blue-800'
                : 'hover:bg-gray-50'
            }
            ${
              isSelectedMonth(index)
                ? 'bg-blue-500 text-white hover:bg-blue-800 shadow-sm'
                : 'text-gray-700'
            }
          `}
          onClick={() => handleMonthSelect(index)}
        >
          {month.slice(0, 3)}
        </div>
      ))}
    </div>
  )

  const renderYearsView = () => {
    const currentYear = currentMonth.getFullYear()
    const decade = Math.floor(currentYear / 10) * 10
    const years = Array.from({ length: 12 }, (_, i) => decade + i - 1)

    return (
      <div className="grid grid-cols-3 gap-2 p-4">
        {years.map((year) => (
          <div
            key={year}
            className={`
              py-3 text-center cursor-pointer text-sm rounded-lg
              transition-all duration-200
              ${
                year === getKualaLumpurDate().getFullYear()
                  ? 'border border-blue-500 text-blue-800'
                  : 'hover:bg-gray-50'
              }
              ${
                year === currentYear
                  ? 'bg-blue-500 text-white hover:bg-blue-800 shadow-sm'
                  : 'text-gray-700'
              }
            `}
            onClick={() => handleYearSelect(year)}
          >
            {year}
          </div>
        ))}
      </div>
    )
  }

  const renderDaysView = () => (
    <div className="p-4">
      <div className="grid grid-cols-7 mb-2">
        {weekDays.map((day) => (
          <div
            key={day}
            className="text-center text-xs font-semibold text-gray-500 py-2"
          >
            {day}
          </div>
        ))}
      </div>
      <div className="grid grid-cols-7 gap-1">
        {getDaysInMonth().map((date, index) => (
          <div
            key={index}
            className={`
              text-center py-1 text-sm rounded-lg
              transition-all duration-200
              ${!date ? 'text-gray-300' : isSelected(date) ? '' : 'hover:bg-gray-100'}
              ${isSelected(date) ? 'bg-blue-800 text-white hover:bg-blue-800 shadow-sm' : ''}
              ${isToday(date) && isSelected(date) ? '!text-white' : isToday(date) ? 'text-blue-800' : ''}
              ${date && !isDateInRange(date) ? 'text-gray-300 cursor-not-allowed hover:!bg-transparent' : 'cursor-pointer'}
            `}
            onClick={() => {
              if (date && isDateInRange(date)) {
                handleDateSelect(date)
              }
            }}
          >
            {date ? date.getDate() : ''}
          </div>
        ))}
      </div>
    </div>
  )

  return (
    <div className="relative w-full" ref={datePickerRef}>
      <div className="relative">
        <input
          readOnly
          disabled={disabled}
          value={formatDisplayDate(selectedDate)}
          className={`flex w-full items-center justify-between py-2 px-3 border border-gray-200 rounded-lg ${
            disabled
              ? 'cursor-not-allowed bg-gray-100 text-gray-500'
              : 'hover:bg-gray-100 focus:ring-2 focus:border-transparent focus:ring-blue-800 transition-all duration-200 bg-white cursor-pointer focus:outline-none text-black'
          } text-sm sm:text-base h-10 sm:h-12`}
          onClick={(e) => {
            e.preventDefault()
            if (!disabled) setIsOpen(!isOpen)
          }}
        />
        <div className="absolute right-3 top-1/2 transform -translate-y-1/2 pointer-events-none">
          <Calendar
            className={`w-4 h-4 ${disabled ? 'text-gray-500' : 'text-black'}`}
          />
        </div>
      </div>

      {isOpen && (
        <div className="absolute z-10 w-64 mt-2 bg-white rounded-xl shadow-lg border border-gray-200 overflow-hidden transition-all duration-200">
          {renderHeader()}

          {viewMode === 'days' && renderDaysView()}
          {viewMode === 'months' && renderMonthsView()}
          {viewMode === 'years' && renderYearsView()}
        </div>
      )}
    </div>
  )
}

export default DatePicker
