'use client'

import React, { useState, useRef, useLayoutEffect, useEffect } from 'react'
import ReactDOM from 'react-dom'
import { CalendarArrowUp, ChevronDown } from 'lucide-react'
import { CustomInput } from './CustomInput'
import { Calendar } from './calendar'
import { cn } from '@/lib/utils/cn'

function roundToNearestQuarter(date: Date) {
  const rounded = new Date(date);
  const minutes = date.getMinutes();
  let newMinutes = 0;

  if (minutes >= 30) {
    rounded.setHours(rounded.getHours() + 1);
    newMinutes = 0;
  } else if (minutes >= 15) {
    newMinutes = 30;
  }

  rounded.setMinutes(newMinutes);
  rounded.setSeconds(0);
  rounded.setMilliseconds(0);
  return rounded;
}


interface CalendarWithTriggerProps {
  className?: string
  placeholder?: string
  label?: string
  hideTime?: boolean
  value?: Date
  onChange: (date: Date) => void
  hasError?: boolean
  errorMessage?: string
  bookedDates?: []
}

export const CalendarWithTrigger: React.FC<CalendarWithTriggerProps> = ({
  className = '',
  placeholder,
  label,
  hideTime = false,
  value,
  onChange,
  hasError,
  errorMessage,
  bookedDates,
}) => {
  const [open, setOpen] = useState(false)
  const inputRef = useRef<HTMLInputElement>(null)
  const wrapperRef = useRef<HTMLDivElement>(null)
  const calendarRef = useRef<HTMLDivElement>(null)
  const [coords, setCoords] = useState<{ top: number; left: number }>({ top: 0, left: 0 })
  const [isTabletView, setIsTabletView] = useState(false)
  useEffect(() => {
    const handleResize = () => {
      const width = window.innerWidth
      setIsTabletView(width >= 1024 && width <= 1180)
    }

    handleResize()

    window.addEventListener('resize', handleResize)
    return () => window.removeEventListener('resize', handleResize)
  }, [])

  useLayoutEffect(() => {
    if (open && inputRef.current) {
      const rect = inputRef.current.getBoundingClientRect()
      setCoords({ top: rect.bottom + window.scrollY, left: rect.left + window.scrollX })
    }
  }, [open])

  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      const target = event.target as Node
      if (
        open &&
        wrapperRef.current &&
        !wrapperRef.current.contains(target) &&
        calendarRef.current &&
        !calendarRef.current.contains(target)
      ) {
        setOpen(false)
      }
    }
    document.addEventListener('mousedown', handleClickOutside)
    return () => document.removeEventListener('mousedown', handleClickOutside)
  }, [open])

  const handleCancel = () => {
    setOpen(false)
  }

  const formatDate = (date: Date) =>
    date.toLocaleDateString('en-GB', { day: '2-digit', month: '2-digit', year: 'numeric' })
  const formatTime = (date: Date) =>
    date.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' })

  const roundedValue = value ? roundToNearestQuarter(value) : undefined;

  const displayValue = roundedValue
    ? !hideTime
      ? isTabletView
        ? `${formatDate(roundedValue)} ${formatTime(roundedValue)}`
        : `${formatDate(roundedValue)}    |    ${formatTime(roundedValue)}`
      : formatDate(roundedValue)
    : ''

  const handleChoose = (dateTime: Date) => {
    onChange(dateTime)
    setOpen(false)
  }

  


  return (
    <div ref={wrapperRef} className={`relative inline-block ${className}`}>
      <CustomInput
        ref={inputRef}
        className={cn('cursor-pointer', isTabletView && 'pr-5', className)}
        iconLeft={<CalendarArrowUp size={20} className="stroke-grey-200" />}
        iconRight={<ChevronDown width={20} className="stroke-grey-200" />}
        label={label}
        placeholder={placeholder}
        readOnly
        value={displayValue}
        onClick={() => setOpen(true)}
        hasError={hasError}
        errorMessage={errorMessage}
      />

      {open &&
        inputRef.current &&
        ReactDOM.createPortal(
          <div
            ref={calendarRef}
            style={{
              position: 'absolute',
              top: coords.top + 'px',
              left: coords.left + 'px',
              zIndex: 9999,
            }}
          >
            <Calendar
              hideTime={hideTime}
              value={hideTime ? value : roundedValue}
              onChange={handleChoose}
              onCancel={handleCancel}
              bookedDates={bookedDates}
            />
          </div>,
          document.body,
        )}
    </div>
  )
}

export default CalendarWithTrigger
