// components/datetime-picker.tsx
import { useEffect, useState } from 'react'
import { Calendar as CalendarIcon, Clock } from 'lucide-react'
import { format } from 'date-fns'
import { cn } from '@/lib/utils'
import { Button } from '@/components/ui/button'
import { Calendar } from '@/components/ui/calendar'
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from '@/components/ui/popover'
import { ScrollArea } from '@/components/ui/scroll-area'

interface DateTimePickerProps {
  value?: Date
  onChange: (date: Date | undefined) => void
  disabled?: boolean
  className?: string
  placeholder?: string
  minDate?: Date
}

export function DateTimePicker({
  value,
  onChange,
  disabled,
  className,
  placeholder = 'Pick a date and time',
  minDate,
}: DateTimePickerProps) {
  const [open, setOpen] = useState(false)
  const [selectedDate, setSelectedDate] = useState<Date | undefined>(value)
  const [selectedTime, setSelectedTime] = useState<{
    hour: string
    minute: string
    period: 'AM' | 'PM'
  }>({
    hour: '12',
    minute: '00',
    period: 'AM',
  })

  useEffect(() => {
    if (value) {
      setSelectedDate(value)
      const hours = value.getHours()
      const minutes = value.getMinutes()
      
      setSelectedTime({
        hour: hours > 12 ? String(hours - 12).padStart(2, '0') : hours === 0 ? '12' : String(hours).padStart(2, '0'),
        minute: String(minutes).padStart(2, '0'),
        period: hours >= 12 ? 'PM' : 'AM',
      })
    }
  }, [value])

  const hours = Array.from({ length: 12 }, (_, i) =>
    String(i + 1).padStart(2, '0')
  )
  const minutes = Array.from({ length: 60 }, (_, i) =>
    String(i).padStart(2, '0')
  )

  const handleDateSelect = (date: Date | undefined) => {
    setSelectedDate(date)
  }

  const isDateDisabled = (date: Date) => {
    if (!minDate) return false
    const compareDate = new Date(date)
    const compareMinDate = new Date(minDate)
    compareDate.setHours(0, 0, 0, 0)
    compareMinDate.setHours(0, 0, 0, 0)
    return compareDate < compareMinDate
  }

  const handleTimeChange = (
    type: 'hour' | 'minute' | 'period',
    newValue: string
  ) => {
    setSelectedTime((prev) => ({
      ...prev,
      [type]: newValue,
    }))
  }

  const handleApply = () => {
    if (selectedDate) {
      const newDate = new Date(selectedDate)
      let hour = parseInt(selectedTime.hour)
      
      if (selectedTime.period === 'PM' && hour !== 12) {
        hour += 12
      } else if (selectedTime.period === 'AM' && hour === 12) {
        hour = 0
      }
      
      newDate.setHours(hour)
      newDate.setMinutes(parseInt(selectedTime.minute))
      newDate.setSeconds(0)
      newDate.setMilliseconds(0)
      
      onChange(newDate)
      setOpen(false)
    }
  }

  const handleClear = () => {
    setSelectedDate(undefined)
    onChange(undefined)
    setSelectedTime({
      hour: '12',
      minute: '00',
      period: 'AM',
    })
    setOpen(false)
  }

  return (
    <Popover open={open} onOpenChange={setOpen}>
      <PopoverTrigger asChild>
        <Button
          variant="outline"
          disabled={disabled}
          className={cn(
            'w-full justify-start text-left font-normal h-11',
            !value && 'text-muted-foreground',
            className
          )}
        >
          <CalendarIcon className="mr-2 h-4 w-4" />
          {value ? (
            format(value, 'PPP p')
          ) : (
            <span>{placeholder}</span>
          )}
        </Button>
      </PopoverTrigger>
      <PopoverContent className="w-auto p-0" align="start" side="bottom" sideOffset={8}>
        <div className="flex flex-col md:flex-row overflow-hidden rounded-md border shadow-xl bg-card">
          {/* Calendar Section */}
          <div className="border-r bg-card">
            <Calendar
              mode="single"
              selected={selectedDate}
              onSelect={handleDateSelect}
              initialFocus
              disabled={isDateDisabled}
            />
          </div>

          {/* Time Section */}
          <div className="flex flex-col p-4 gap-4 bg-card min-w-[240px]">
            <div className="flex items-center gap-2 pb-2 border-b">
              <Clock className="h-4 w-4 text-muted-foreground" />
              <span className="text-sm font-medium">Select Time</span>
            </div>

            <div className="flex gap-3 justify-center">
              {/* Hour Picker */}
              <div className="flex flex-col items-center gap-2">
                <label className="text-[10px] font-medium text-muted-foreground">
                  Hour
                </label>
                <ScrollArea className="h-40 w-14 rounded-md border bg-muted/5">
                  <div className="p-1">
                    {hours.map((h) => (
                      <button
                        key={h}
                        type="button"
                        onClick={() => handleTimeChange('hour', h)}
                        className={cn(
                          'w-full rounded px-2 py-1.5 text-xs font-medium hover:bg-primary/10 transition-colors',
                          selectedTime.hour === h &&
                            'bg-primary text-primary-foreground shadow-lg shadow-primary/20'
                        )}
                      >
                        {h}
                      </button>
                    ))}
                  </div>
                </ScrollArea>
              </div>

              {/* Minute Picker */}
              <div className="flex flex-col items-center gap-2">
                <label className="text-[10px] font-medium text-muted-foreground ">
                  Min
                </label>
                <ScrollArea className="h-40 w-14 rounded-md border bg-muted/5">
                  <div className="p-1">
                    {minutes.filter(m => parseInt(m) % 5 === 0).map((m) => (
                      <button
                        key={m}
                        type="button"
                        onClick={() => handleTimeChange('minute', m)}
                        className={cn(
                          'w-full rounded px-2 py-1.5 text-xs font-medium hover:bg-primary/10 transition-colors',
                          selectedTime.minute === m &&
                            'bg-primary text-primary-foreground shadow-lg shadow-primary/20'
                        )}
                      >
                        {m}
                      </button>
                    ))}
                  </div>
                </ScrollArea>
              </div>

              {/* Period Picker */}
              <div className="flex flex-col items-center gap-2">
                <label className="text-[10px] font-medium text-muted-foreground ">
                  &nbsp;
                </label>
                <div className="flex flex-col gap-2 pt-1">
                  {(['AM', 'PM'] as const).map((p) => (
                    <button
                      key={p}
                      type="button"
                      onClick={() => handleTimeChange('period', p)}
                      className={cn(
                        'w-12 rounded px-2 py-2 text-xs font-mediumhover:bg-primary/10 transition-colors border',
                        selectedTime.period === p
                          ? 'bg-primary text-primary-foreground border-primary shadow-lg shadow-primary/20'
                          : 'border-transparent'
                      )}
                    >
                      {p}
                    </button>
                  ))}
                </div>
              </div>
            </div>

            {/* Action Buttons */}
            <div className="flex gap-2 pt-4 border-t mt-auto">
              <Button
                type="button"
                variant="outline"
                size="sm"
                onClick={handleClear}
                className="flex-1 rounded h-9 font-semibold"
              >
                Clear
              </Button>
              <Button
                type="button"
                size="sm"
                onClick={handleApply}
                disabled={!selectedDate}
                className="flex-1 rounded h-9 font-mediumbg-primary"
              >
                Apply
              </Button>
            </div>
          </div>
        </div>
      </PopoverContent>
    </Popover>
  )
}
