import * as React from "react"
import {
  add,
  eachDayOfInterval,
  endOfMonth,
  format,
  getDay,
  isEqual,
  isSameDay,
  isSameMonth,
  isToday,
  parse,
  startOfToday,
  startOfWeek,
  setMonth,
} from "date-fns"
import {
  ChevronLeftIcon,
  ChevronRightIcon,
  Stethoscope,
  Syringe,
  Pill,
  Beaker,
  ImageIcon,
  X,
  Clock,
  type LucideIcon,
} from "lucide-react"
import { cn } from "../utils/helpers"
import { formatSpecificTime } from "../utils/eventTime"
import type {
  TimelineEvent,
  EventType,
  Appointment,
  LabResult,
  Medication,
  ImagingEvent,
} from "../types/medical"

type DisplayedEventType = Exclude<EventType, "vitals">

const EVENT_COLORS: Record<DisplayedEventType, { bg: string; text: string; border: string; dot: string; badge: string; accent: string }> = {
  appointments: {
    bg: "bg-blue-50",
    text: "text-blue-700",
    border: "border-blue-200",
    dot: "bg-blue-500",
    badge: "bg-blue-100 text-blue-700 border-blue-200",
    accent: "bg-blue-500",
  },
  labs: {
    bg: "bg-rose-50",
    text: "text-rose-700",
    border: "border-rose-200",
    dot: "bg-rose-500",
    badge: "bg-rose-100 text-rose-700 border-rose-200",
    accent: "bg-rose-500",
  },
  prescriptions: {
    bg: "bg-emerald-50",
    text: "text-emerald-700",
    border: "border-emerald-200",
    dot: "bg-emerald-500",
    badge: "bg-emerald-100 text-emerald-700 border-emerald-200",
    accent: "bg-emerald-500",
  },
  vaccinations: {
    bg: "bg-purple-50",
    text: "text-purple-700",
    border: "border-purple-200",
    dot: "bg-purple-500",
    badge: "bg-purple-100 text-purple-700 border-purple-200",
    accent: "bg-purple-500",
  },
  imaging: {
    bg: "bg-sky-50",
    text: "text-sky-700",
    border: "border-sky-200",
    dot: "bg-sky-500",
    badge: "bg-sky-100 text-sky-700 border-sky-200",
    accent: "bg-sky-500",
  },
}

const EVENT_ICONS: Record<DisplayedEventType, LucideIcon> = {
  appointments: Stethoscope,
  labs: Beaker,
  prescriptions: Pill,
  vaccinations: Syringe,
  imaging: ImageIcon,
}

function getEventName(event: TimelineEvent): string {
  switch (event.type) {
    case "appointments":
      return (event as Appointment).reason
    case "labs":
      return (event as LabResult).testName
    case "prescriptions":
      return (event as Medication).name
    case "vaccinations":
      return (event as import('../types/medical').VaccinationEvent).name
    case "imaging":
      return (event as ImagingEvent).name
    default:
      return "Event"
  }
}

function getEventTime(event: TimelineEvent): string {
  return "time" in event ? formatSpecificTime(event.time) : ""
}

function getEventSubtext(event: TimelineEvent): string {
  switch (event.type) {
    case "appointments":
      return (event as Appointment).doctor
    case "labs":
      return (event as LabResult).orderingPhysician
    case "prescriptions":
      return (event as Medication).dosage
    case "vaccinations":
      return (event as import('../types/medical').VaccinationEvent).administrationPlace || 'Vaccination'
    case "imaging":
      return (event as ImagingEvent).hospital || 'Imaging'
    default:
      return ""
  }
}

interface CalendarData {
  day: Date
  events: TimelineEvent[]
}

interface FullScreenCalendarProps {
  data: CalendarData[]
  onEventClick?: (event: TimelineEvent) => void
}

const colStartClasses = [
  "",
  "col-start-2",
  "col-start-3",
  "col-start-4",
  "col-start-5",
  "col-start-6",
  "col-start-7",
]

export function FullScreenCalendar({ data, onEventClick }: FullScreenCalendarProps) {
  const today = startOfToday()
  const [selectedDay, setSelectedDay] = React.useState(today)
  const [currentMonth, setCurrentMonth] = React.useState(
    format(today, "MMM-yyyy")
  )
  const firstDayCurrentMonth = parse(currentMonth, "MMM-yyyy", new Date())
  // Always 6 weeks (42 days) so grid height never changes
  const calendarStart = startOfWeek(firstDayCurrentMonth)
  const days = eachDayOfInterval({
    start: calendarStart,
    end: add(calendarStart, { days: 41 }),
  })

  const [viewMode, setViewMode] = React.useState<'month' | 'year'>('month')
  const [activeFilters, setActiveFilters] = React.useState<DisplayedEventType[]>([
    'appointments', 'labs', 'prescriptions', 'vaccinations', 'imaging'
  ])

  function toggleFilter(type: DisplayedEventType) {
    setActiveFilters(prev =>
      prev.includes(type) ? prev.filter(t => t !== type) : [...prev, type]
    )
  }

  const filteredData = React.useMemo(() => {
    return data.map(d => ({
      ...d,
      events: d.events.filter(e => (activeFilters as EventType[]).includes(e.type))
    }))
  }, [data, activeFilters])

  function previous() {
    if (viewMode === 'month') {
      const firstDayNextMonth = add(firstDayCurrentMonth, { months: -1 })
      setCurrentMonth(format(firstDayNextMonth, "MMM-yyyy"))
    } else {
      const prevYear = add(firstDayCurrentMonth, { years: -1 })
      setCurrentMonth(format(prevYear, "MMM-yyyy"))
    }
    setShowPopover(false)
  }

  function next() {
    if (viewMode === 'month') {
      const firstDayNextMonth = add(firstDayCurrentMonth, { months: 1 })
      setCurrentMonth(format(firstDayNextMonth, "MMM-yyyy"))
    } else {
      const nextYear = add(firstDayCurrentMonth, { years: 1 })
      setCurrentMonth(format(nextYear, "MMM-yyyy"))
    }
    setShowPopover(false)
  }

  function goToToday() {
    setCurrentMonth(format(today, "MMM-yyyy"))
    setSelectedDay(today)
    setShowPopover(false)
  }

  // Popover state
  const [showPopover, setShowPopover] = React.useState(false)
  const [popoverPos, setPopoverPos] = React.useState<{ top: number; left: number; alignRight: boolean; alignBottom: boolean }>({ top: 0, left: 0, alignRight: false, alignBottom: false })
  const calendarRef = React.useRef<HTMLDivElement>(null)

  const selectedDayEvents = React.useMemo(() => {
    return filteredData
      .filter((d) => isSameDay(d.day, selectedDay))
      .flatMap((d) => d.events)
      .sort((a, b) => {
        const aTime = getEventTime(a) || '00:00';
        const bTime = getEventTime(b) || '00:00';
        return aTime.localeCompare(bTime);
      })
  }, [filteredData, selectedDay])

  function handleDayClick(day: Date, e: React.MouseEvent<HTMLElement>) {
    const dayEvents = filteredData
      .filter((d) => isSameDay(d.day, day))
      .flatMap((d) => d.events)

    if (dayEvents.length === 0) {
      setSelectedDay(day)
      setShowPopover(false)
      return
    }

    // If clicking the same day, toggle
    if (isEqual(day, selectedDay) && showPopover) {
      setShowPopover(false)
      return
    }

    setSelectedDay(day)

    // Position popover relative to the calendar container
    const cell = (e.currentTarget as HTMLElement)
    const calendarRect = calendarRef.current?.getBoundingClientRect()
    const cellRect = cell.getBoundingClientRect()

    if (calendarRect) {
      const cellCenterX = cellRect.left + cellRect.width / 2 - calendarRect.left
      const cellBottom = cellRect.bottom - calendarRect.top
      const cellTop = cellRect.top - calendarRect.top

      // Decide if popover should go up or down
      const spaceBelow = calendarRect.height - cellBottom
      const alignBottom = spaceBelow < 220

      // Decide if popover should align left or right
      const alignRight = cellCenterX > calendarRect.width / 2

      setPopoverPos({
        top: alignBottom ? cellTop : cellBottom + 4,
        left: alignRight ? cellCenterX : cellCenterX,
        alignRight,
        alignBottom,
      })
    }

    setShowPopover(true)
  }

  // Close popover on Escape
  React.useEffect(() => {
    if (!showPopover) return
    function handleEsc(e: KeyboardEvent) {
      if (e.key === "Escape") setShowPopover(false)
    }
    window.addEventListener("keydown", handleEsc)
    return () => {
      window.removeEventListener("keydown", handleEsc)
    }
  }, [showPopover])

  return (
    <div ref={calendarRef} className="relative flex flex-1 flex-col bg-white rounded-2xl shadow-sm border border-slate-100 overflow-visible">
      {/* Calendar Header */}
      <div className="flex flex-col space-y-4 p-4 md:flex-row md:items-center md:justify-between md:space-y-0 lg:flex-none border-b border-slate-100">
        <div className="flex flex-auto">
          <div className="flex items-center gap-4">
            {viewMode === 'month' ? (
              <>
                <div className="hidden w-20 flex-col items-center justify-center rounded-lg border border-slate-200 bg-slate-50 p-0.5 md:flex">
                  <h1 className="p-1 text-xs uppercase text-slate-500">
                    {format(today, "MMM")}
                  </h1>
                  <div className="flex w-full items-center justify-center rounded-lg border border-slate-200 bg-white p-0.5 text-lg font-bold text-slate-800">
                    <span>{format(today, "d")}</span>
                  </div>
                </div>
                <div 
                  className="flex flex-col cursor-pointer hover:bg-slate-50 p-2 -ml-2 rounded-lg transition-colors"
                  onClick={() => setViewMode('year')}
                  title="Switch to Year view"
                >
                  <h2 className="text-lg font-semibold text-slate-800 flex items-center gap-2">
                    {format(firstDayCurrentMonth, "MMMM, yyyy")}
                    <span className="text-[10px] bg-slate-100 text-slate-500 px-1.5 py-0.5 rounded uppercase font-bold tracking-wide">Month View</span>
                  </h2>
                  <p className="text-sm text-slate-500">
                    {format(firstDayCurrentMonth, "MMM d, yyyy")} -{" "}
                    {format(endOfMonth(firstDayCurrentMonth), "MMM d, yyyy")}
                  </p>
                </div>
              </>
            ) : (
              <div 
                className="flex flex-col cursor-pointer hover:bg-slate-50 p-2 -ml-2 rounded-lg transition-colors"
                onClick={() => setViewMode('month')}
                title="Switch to Month view"
              >
                <h2 className="text-lg font-semibold text-slate-800 flex items-center gap-2">
                  {format(firstDayCurrentMonth, "yyyy")}
                  <span className="text-[10px] bg-blue-100 text-blue-600 px-1.5 py-0.5 rounded uppercase font-bold tracking-wide">Year View</span>
                </h2>
                <p className="text-sm text-slate-500">
                  Select a month to view details
                </p>
              </div>
            )}
          </div>
        </div>
        <div className="flex flex-col items-center gap-4 md:flex-row md:gap-4">
          <div className="inline-flex w-full -space-x-px rounded-lg shadow-sm shadow-black/5 md:w-auto rtl:space-x-reverse">
            <button
              onClick={previous}
              className="inline-flex items-center justify-center h-9 w-9 rounded-l-lg border border-slate-200 bg-white text-slate-600 hover:bg-slate-50 transition-colors"
              aria-label={viewMode === 'month' ? "Navigate to previous month" : "Navigate to previous year"}
            >
              <ChevronLeftIcon size={16} strokeWidth={2} />
            </button>
            <button
              onClick={goToToday}
              className="inline-flex items-center justify-center h-9 px-4 border-y border-slate-200 bg-white text-sm font-medium text-slate-700 hover:bg-slate-50 transition-colors"
            >
              Today
            </button>
            <button
              onClick={next}
              className="inline-flex items-center justify-center h-9 w-9 rounded-r-lg border border-slate-200 bg-white text-slate-600 hover:bg-slate-50 transition-colors"
              aria-label={viewMode === 'month' ? "Navigate to next month" : "Navigate to next year"}
            >
              <ChevronRightIcon size={16} strokeWidth={2} />
            </button>
          </div>

          <div className="hidden h-6 w-px bg-slate-200 md:block" />
          <div className="hidden md:flex items-center gap-0.5 rounded-lg border border-slate-200 bg-slate-100 p-0.5">
            {(Object.keys(EVENT_COLORS) as DisplayedEventType[]).map((type) => {
              const Icon = EVENT_ICONS[type]
              const isActive = activeFilters.includes(type)
              return (
                <button 
                  key={type} 
                  onClick={() => toggleFilter(type)}
                  className={cn(
                    "flex items-center gap-1.5 rounded-md px-2.5 py-1 text-xs font-medium transition-all",
                    isActive
                      ? "bg-white text-slate-900 shadow-sm"
                      : "text-slate-500 hover:text-slate-800"
                  )}
                  title={isActive ? `Hide ${type}` : `Show ${type}`}
                >
                  <Icon 
                    size={13} 
                    strokeWidth={2}
                    className={isActive ? EVENT_COLORS[type].text : "text-slate-400"} 
                  />
                  <span className="capitalize">{type}</span>
                </button>
              )
            })}
          </div>
        </div>
      </div>

      {/* Calendar Grid */}
      {viewMode === 'month' ? (
        <div className="lg:flex lg:flex-col">
          {/* Week Days Header */}
          <div className="grid grid-cols-7 border-b border-slate-100 text-center text-xs font-semibold leading-6 text-slate-500">
            <div className="border-r border-slate-100 py-2.5">Sun</div>
            <div className="border-r border-slate-100 py-2.5">Mon</div>
            <div className="border-r border-slate-100 py-2.5">Tue</div>
            <div className="border-r border-slate-100 py-2.5">Wed</div>
            <div className="border-r border-slate-100 py-2.5">Thu</div>
            <div className="border-r border-slate-100 py-2.5">Fri</div>
            <div className="py-2.5">Sat</div>
          </div>

          {/* Calendar Days */}
          <div className="flex text-xs leading-6">
            {/* Desktop View */}
            <div className="hidden w-full lg:grid lg:grid-cols-7 lg:grid-rows-6">
              {days.map((day, dayIdx) => {
                const dayEvents = filteredData
                  .filter((event) => isSameDay(event.day, day))
                  .flatMap((d) => d.events)
                const hasEvents = dayEvents.length > 0
                const isSelected = isEqual(day, selectedDay)

                return (
                  <div
                    key={dayIdx}
                    onClick={(e) => handleDayClick(day, e)}
                    className={cn(
                      dayIdx === 0 && colStartClasses[getDay(day)],
                      !isSelected &&
                        !isToday(day) &&
                        !isSameMonth(day, firstDayCurrentMonth) &&
                        "bg-slate-50/80 text-slate-400",
                      "relative flex flex-col border-b border-r border-slate-100 h-[120px] transition-colors cursor-pointer",
                      hasEvents ? "hover:bg-blue-50/40" : "hover:bg-slate-50/50",
                      isSelected && showPopover && "bg-blue-50/60 ring-2 ring-blue-400/60 ring-inset z-10",
                      isSelected && !showPopover && "bg-blue-50/20",
                    )}
                  >
                    <header className="flex items-center justify-between p-2">
                      <span
                        className={cn(
                          "flex h-7 w-7 items-center justify-center rounded-full text-xs select-none",
                          isSelected && isToday(day) && "bg-blue-500 text-white font-bold",
                          isSelected && !isToday(day) && "bg-slate-800 text-white font-semibold",
                          !isSelected && isToday(day) && "bg-blue-100 text-blue-700 font-semibold",
                          !isSelected && !isToday(day) && isSameMonth(day, firstDayCurrentMonth) && "text-slate-700",
                          !isSelected && !isToday(day) && !isSameMonth(day, firstDayCurrentMonth) && "text-slate-400",
                        )}
                      >
                        <time dateTime={format(day, "yyyy-MM-dd")}>
                          {format(day, "d")}
                        </time>
                      </span>
                    </header>

                    <div className="flex-1 px-1.5 pb-1.5 space-y-0.5 overflow-hidden">
                      {dayEvents
                    .sort((a, b) => {
                      const aTime = getEventTime(a) || '00:00';
                      const bTime = getEventTime(b) || '00:00';
                      return aTime.localeCompare(bTime);
                    })
                    .slice(0, 3).map((event) => {
                        const colors = EVENT_COLORS[event.type as DisplayedEventType]
                        const time = getEventTime(event)
                    
                    return (
                      <div
                        key={event.id}
                        onClick={(e) => {
                          e.stopPropagation()
                          onEventClick?.(event)
                        }}
                        className={cn(
                          "flex items-center gap-1 w-full rounded px-1.5 py-0.5 text-[11px] leading-tight text-left transition-all hover:opacity-80 cursor-pointer",
                          colors.bg, colors.text
                        )}
                      >
                        <span className={cn("w-1 h-1 rounded-full shrink-0", colors.accent)} />
                        <span className="truncate flex-1 font-medium">{getEventName(event)}</span>
                        {time && <span className="shrink-0 opacity-75">{time}</span>}
                      </div>
                    )
                  })}
                      {dayEvents.length > 3 && (
                        <div className="text-[10px] text-blue-500 font-semibold pl-2.5 cursor-pointer hover:text-blue-700">
                          +{dayEvents.length - 3} more
                        </div>
                      )}
                    </div>
                  </div>
                )
              })}
            </div>

            {/* Mobile View */}
            <div className="isolate grid w-full grid-cols-7 grid-rows-6 lg:hidden">
              {days.map((day, dayIdx) => (
                <button
                  onClick={(e) => handleDayClick(day, e)}
                  key={dayIdx}
                  type="button"
                  className={cn(
                    "flex h-14 flex-col border-b border-r border-slate-100 px-2 py-1.5 hover:bg-slate-50 focus:z-10 transition-colors",
                    isEqual(day, selectedDay) && "bg-blue-50",
                    !isSameMonth(day, firstDayCurrentMonth) && "text-slate-400",
                  )}
                >
                  <time
                    dateTime={format(day, "yyyy-MM-dd")}
                    className={cn(
                      "ml-auto flex size-6 items-center justify-center rounded-full text-xs",
                      isEqual(day, selectedDay) && isToday(day) && "bg-blue-500 text-white font-bold",
                      isEqual(day, selectedDay) && !isToday(day) && "bg-slate-800 text-white",
                      !isEqual(day, selectedDay) && isToday(day) && "bg-blue-100 text-blue-700 font-semibold",
                    )}
                  >
                    {format(day, "d")}
                  </time>
                  {filteredData.filter((date) => isSameDay(date.day, day)).length > 0 && (
                    <div className="-mx-0.5 mt-auto flex flex-wrap-reverse justify-center">
                      {filteredData
                        .filter((date) => isSameDay(date.day, day))
                        .flatMap((d) => d.events)
                        .sort((a, b) => {
                          const aTime = getEventTime(a) || '00:00';
                          const bTime = getEventTime(b) || '00:00';
                          return bTime.localeCompare(aTime);
                        })
                        .slice(0, 3)
                        .map((event) => (
                          <span
                            key={event.id}
                            className={cn(
                              "mx-0.5 mt-0.5 h-1.5 w-1.5 rounded-full",
                              EVENT_COLORS[event.type as DisplayedEventType].dot
                            )}
                          />
                        ))}
                    </div>
                  )}
                </button>
              ))}
            </div>
          </div>
        </div>
      ) : (
        <div className="p-4 grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4 bg-slate-50/30 rounded-b-2xl">
          {Array.from({ length: 12 }).map((_, i) => {
            const monthDate = setMonth(firstDayCurrentMonth, i)
            const isCurrentMonth = isSameMonth(monthDate, today)
            
            // Count events in this month
            const monthEvents = filteredData.filter(d => isSameMonth(d.day, monthDate)).flatMap(d => d.events)
            const countedEvents = new Set<string>()
            const counts = monthEvents.reduce((acc, ev) => {
              const eventKey = `${ev.type}:${ev.id}`
              if (countedEvents.has(eventKey)) return acc
              countedEvents.add(eventKey)
              acc[ev.type] = (acc[ev.type] || 0) + 1
              return acc
            }, {} as Record<string, number>)

            return (
              <div 
                key={i} 
                onClick={() => {
                  setCurrentMonth(format(monthDate, "MMM-yyyy"))
                  setViewMode('month')
                }}
                className={cn(
                  "border rounded-xl p-4 cursor-pointer hover:-translate-y-0.5 hover:shadow-md transition-all duration-200 bg-white group",
                  isCurrentMonth ? "border-blue-400 ring-1 ring-blue-400/50" : "border-slate-100 hover:border-slate-300"
                )}
              >
                <div className="flex items-center justify-between mb-4">
                  <h3 className={cn(
                    "font-semibold text-lg transition-colors",
                    isCurrentMonth ? "text-blue-600" : "text-slate-800 group-hover:text-blue-600"
                  )}>
                    {format(monthDate, "MMMM")}
                  </h3>
                  {isCurrentMonth && <span className="bg-blue-100 text-blue-700 text-[10px] font-bold uppercase px-1.5 py-0.5 rounded">Current</span>}
                </div>
                
                <div className="space-y-1.5">
                  {Object.keys(counts).length === 0 ? (
                    <div className="text-slate-400 text-sm italic py-2 flex items-center justify-center border border-dashed border-slate-200 rounded-lg bg-slate-50/50">
                      No events
                    </div>
                  ) : (
                    (Object.keys(EVENT_COLORS) as DisplayedEventType[]).map(type => {
                      if (!counts[type]) return null
                      const colors = EVENT_COLORS[type]
                      const Icon = EVENT_ICONS[type]
                      return (
                        <div key={type} className={cn("flex items-center justify-between text-xs px-2 py-1.5 rounded-lg border", colors.bg, colors.text, colors.border)}>
                          <div className="flex items-center gap-2">
                            <Icon size={12} className={colors.text} />
                            <span className="capitalize font-medium">{type}</span>
                          </div>
                          <span className={cn("font-bold px-1.5 rounded-sm bg-white/60", colors.text)}>{counts[type]}</span>
                        </div>
                      )
                    })
                  )}
                </div>
              </div>
            )
          })}
        </div>
      )}

      {/* Day Events Popover */}
      {showPopover && selectedDayEvents.length > 0 && (
        <>
          {/* Backdrop - click to dismiss */}
          <div
            className="fixed inset-0 z-30"
            onClick={() => setShowPopover(false)}
          />

          <div
            id="calendar-day-popover"
            className="absolute z-40 w-72 max-h-80 bg-white rounded-xl shadow-xl border border-slate-200 overflow-hidden"
            style={{
              top: popoverPos.alignBottom ? undefined : `${popoverPos.top}px`,
              bottom: popoverPos.alignBottom ? `${(calendarRef.current?.getBoundingClientRect().height ?? 0) - popoverPos.top + 4}px` : undefined,
              left: popoverPos.alignRight ? undefined : `${popoverPos.left}px`,
              right: popoverPos.alignRight ? `${(calendarRef.current?.getBoundingClientRect().width ?? 0) - popoverPos.left}px` : undefined,
              animation: "popIn 0.15s ease-out",
            }}
          >
            {/* Popover Header */}
            <div className="flex items-center justify-between px-4 py-3 bg-slate-50 border-b border-slate-100">
              <div>
                <p className="text-sm font-semibold text-slate-800">
                  {format(selectedDay, "EEEE")}
                </p>
                <p className="text-xs text-slate-500">
                  {format(selectedDay, "MMMM d, yyyy")}
                </p>
              </div>
              <button
                onClick={() => setShowPopover(false)}
                className="p-1.5 rounded-lg hover:bg-slate-200/70 text-slate-400 hover:text-slate-600 transition-colors"
              >
                <X size={14} />
              </button>
            </div>

            {/* Events list */}
            <div className="overflow-y-auto max-h-56 p-2 space-y-1">
              {selectedDayEvents.map((event) => {
                const colors = EVENT_COLORS[event.type as DisplayedEventType]
                const Icon = EVENT_ICONS[event.type as DisplayedEventType]
                const time = getEventTime(event)
                const subtext = getEventSubtext(event)

                return (
                  <button
                    key={event.id}
                    onClick={() => {
                      setShowPopover(false)
                      onEventClick?.(event)
                    }}
                    className="flex items-start gap-3 w-full p-2.5 rounded-lg text-left transition-all hover:bg-slate-50 group"
                  >
                    <div className={cn(
                      "mt-0.5 p-1.5 rounded-lg shrink-0 transition-colors",
                      colors.bg,
                      "group-hover:shadow-sm"
                    )}>
                      <Icon size={14} className={colors.text} />
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="text-[13px] font-medium text-slate-800 truncate leading-tight">
                        {getEventName(event)}
                      </p>
                      <div className="flex items-center gap-2 mt-0.5">
                        {time && (
                          <span className="flex items-center gap-1 text-[11px] text-slate-400">
                            <Clock size={9} />
                            {time}
                          </span>
                        )}
                        {subtext && (
                          <span className="text-[11px] text-slate-400 truncate">
                            {subtext}
                          </span>
                        )}
                      </div>
                    </div>
                    <span className={cn(
                      "text-[9px] px-1.5 py-0.5 rounded-full font-semibold capitalize shrink-0 mt-0.5",
                      colors.badge
                    )}>
                      {event.type === "appointments" ? "Appt" : event.type === "prescriptions" ? "Med" : event.type === "labs" ? "Lab" : event.type === "vaccinations" ? "Vax" : event.type === "imaging" ? "Img" : ""}
                    </span>
                  </button>
                )
              })}
            </div>
          </div>

          <style>{`
            @keyframes popIn {
              from { opacity: 0; transform: scale(0.95) translateY(4px); }
              to { opacity: 1; transform: scale(1) translateY(0); }
            }
          `}</style>
        </>
      )}
    </div>
  )
}
