"use client"
import AppointmentSlot from "./AppointmentSlot"
import { startOfWeek, endOfWeek, startOfMonth, endOfMonth, eachDayOfInterval } from "date-fns"
import { useState, useCallback, useRef } from "react"
import { cn } from "@/lib/utils"
import { Sheet, SheetContent, SheetTitle } from "@/components/ui/sheet"
import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar"
import { Button } from "@/components/ui/button"
import { Edit, Trash2, GripVertical, Loader2 } from "lucide-react"
import UpdateBookingModal from "./UpdateBookingModal"
import { useTranslations, useFormatter, useLocale } from "next-intl"
import { useRouter } from "next/navigation"
import { useAuth } from "@/context/AuthContext"
import { useModifyAppointment } from "@/lib/react-query/hooks/appointments"
import { useToaster } from "@/context/ToasterContext"
import { useConfirm } from "@/context/ConfirmDialogContext"

interface StaffMember {
  id: number
  name: string
  avatar: string
  title?: string
}

interface Appointment {
  id: number
  bookingId: string
  staffId: number
  date: Date
  dateKey: string
  startTime: string
  endTime: string
  clientName: string
  service: string
  status: string
  color: "cyan" | "orange" | "teal" | "pink"
  generatedBy?: string
  clientId?: string
  serviceId?: string
  salonId?: string
  realStylistId?: string
  offerId?: string
}

interface CalendarGridProps {
  staffMembers: StaffMember[]
  timeSlots: { [key: string]: Appointment[] }
  date: Date
  activeTab: string
  allAppointments: Appointment[]
  services?: { value: string; label: string; description: string }[]
  clients?: { value: string; label: string; description: string }[]
  onAppointmentUpdate?: () => void
}

// Format local Date to YYYY-MM-DD in specific timezone
const formatLocalDate = (date: Date) => {
  const y = date.getFullYear()
  const m = String(date.getMonth() + 1).padStart(2, "0")
  const d = String(date.getDate()).padStart(2, "0")
  return `${y}-${m}-${d}`
}

export function CalendarGrid({ staffMembers, timeSlots, date, activeTab, allAppointments, services, clients, onAppointmentUpdate }: CalendarGridProps) {
  const [isUpdateModalOpen, setIsUpdateModalOpen] = useState(false)
  const [selectedAppointment, setSelectedAppointment] = useState<Appointment | null>(null)
  const [cancellingAppointmentId, setCancellingAppointmentId] = useState<number | null>(null)
  const t = useTranslations()
  const formatter = useFormatter()
  const locale = useLocale()
  const { user } = useAuth()
  const modifyAppointmentMutation = useModifyAppointment()
  const router = useRouter()
  const toast = useToaster()
  const confirm = useConfirm()
  const todayKey = formatLocalDate(new Date())

  // Drag and drop state
  const [draggedAppointment, setDraggedAppointment] = useState<Appointment | null>(null)
  const [dragOverCell, setDragOverCell] = useState<string | null>(null)
  const [isDroppingAppointment, setIsDroppingAppointment] = useState(false)
  const dragCounterRef = useRef<{ [key: string]: number }>({})

  const timeSlotKeys = Object.keys(timeSlots).sort()

  const generateAllTimeSlots = () => {
    const slots = []
    for (let hour = 6; hour <= 24; hour++) {
      slots.push(`${hour.toString().padStart(2, '0')}:00`)
    }
    return slots
  }

  const filterPastTimeSlots = (slots: string[], currentDate: Date) => {
    const today = new Date()
    const isToday = currentDate.getDate() === today.getDate() &&
      currentDate.getMonth() === today.getMonth() &&
      currentDate.getFullYear() === today.getFullYear()

    if (!isToday) {
      return slots
    }

    const currentHour = today.getHours()
    return slots.filter(slot => {
      const slotHour = parseInt(slot.split(':')[0])
      return slotHour >= currentHour
    })
  }

  const allTimeSlots = activeTab === "daily"
    ? filterPastTimeSlots(generateAllTimeSlots(), date)
    : generateAllTimeSlots()
  const columnWidth = "160px"
  const rowHeaderWidth = "120px"
  const minStaffColumns = 7
  const totalGridWidth = `${120 + minStaffColumns * 160}px`

  const generateStaffColumns = () => {
    const columns = []
    for (let i = 0; i < minStaffColumns; i++) {
      const staff = staffMembers[i]
      if (staff) {
        columns.push(staff)
      } else {
        columns.push({
          id: `empty-${i}`,
          name: "",
          avatar: "",
          title: ""
        })
      }
    }
    return columns
  }

  const displayStaffMembers = generateStaffColumns()

  const [isDrawerOpen, setIsDrawerOpen] = useState(false)
  const [drawerData, setDrawerData] = useState<{
    appointments: Appointment[]
    staffName: string
    staffAvatar: string
    dayLabel: string
    bookingType: string
  }>({
    appointments: [],
    staffName: "",
    staffAvatar: "",
    dayLabel: "",
    bookingType: ""
  })

  const formatTimeTo24H = (
    timeString: string,
    locale: string = 'en-GB'
  ): string => {
    if (timeString.includes('T')) {
      const date = new Date(timeString)

      if (user?.timezone) {
        try {
          const formattedTime = new Intl.DateTimeFormat(locale, {
            timeZone: user.timezone,
            hour: '2-digit',
            minute: '2-digit',
            hour12: false,
          }).format(date)
          return formattedTime
        } catch (error) {
          console.error('Error formatting time:', error)
        }
      }

      const hours = date.getHours()
      const minutes = date.getMinutes()
      return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`
    }

    const [hours, minutes] = timeString.split(':').map(Number)
    return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`
  }

  const openDrawer = (appointments: Appointment[], staffName: string, staffAvatar: string, dayLabel: string, bookingType: string) => {
    setDrawerData({
      appointments,
      staffName,
      staffAvatar,
      dayLabel,
      bookingType
    })
    setIsDrawerOpen(true)
  }

  const closeDrawer = () => {
    setIsDrawerOpen(false)
    setDrawerData({
      appointments: [],
      staffName: "",
      staffAvatar: "",
      dayLabel: "",
      bookingType: ""
    })
  }

  const openUpdateModal = (appointment: Appointment) => {
    setSelectedAppointment(appointment)
    setIsUpdateModalOpen(true)
    closeDrawer()
  }

  const closeUpdateModal = () => {
    setIsUpdateModalOpen(false)
    setSelectedAppointment(null)
  }

  const handleAppointmentUpdate = () => {
    onAppointmentUpdate?.()
    closeUpdateModal()
  }

  const handleCancelAppointment = (appointment: Appointment) => {
    confirm.show({
      title: t("calendar.modals.cancelAppointment"),
      description: t("calendar.modals.confirmCancelAppointment", {
        client: appointment.clientName
      }),
      confirmText: t("common.confirm"),
      cancelText: t("common.cancel"),
      onConfirm: () => {
        setCancellingAppointmentId(appointment.id)

        modifyAppointmentMutation.mutate({
          bookingId: appointment.bookingId,
          delete: true
        }, {
          onSuccess: () => {
            setCancellingAppointmentId(null)
            closeDrawer()
            onAppointmentUpdate?.()
          },
          onError: () => {
            setCancellingAppointmentId(null)
          }
        })
      }
    })
  }

  const getWeekDays = (date: Date) => {
    const start = startOfWeek(date, { weekStartsOn: 1 })
    const end = endOfWeek(start, { weekStartsOn: 1 })
    return eachDayOfInterval({ start, end })
  }

  const getMonthDays = (date: Date) => {
    const start = startOfMonth(date)
    const end = endOfMonth(date)
    return eachDayOfInterval({ start, end })
  }

  // ===== DRAG AND DROP HANDLERS =====

  const handleDragStart = useCallback((e: React.DragEvent, appointment: Appointment) => {
    // Only allow dragging for non-cancelled, future appointments
    if (appointment.status === 'cancelled' || new Date(appointment.startTime) <= new Date()) {
      e.preventDefault()
      return
    }

    setDraggedAppointment(appointment)
    e.dataTransfer.effectAllowed = 'move'
    e.dataTransfer.setData('text/plain', JSON.stringify({
      bookingId: appointment.bookingId,
      id: appointment.id
    }))

    // Create a custom drag image
    const dragEl = e.currentTarget as HTMLElement
    if (dragEl) {
      const rect = dragEl.getBoundingClientRect()
      e.dataTransfer.setDragImage(dragEl, rect.width / 2, rect.height / 2)
    }
  }, [])

  const handleDragEnd = useCallback(() => {
    setDraggedAppointment(null)
    setDragOverCell(null)
    dragCounterRef.current = {}
  }, [])

  const handleDragOver = useCallback((e: React.DragEvent) => {
    e.preventDefault()
    e.dataTransfer.dropEffect = 'move'
  }, [])

  const handleDragEnter = useCallback((e: React.DragEvent, cellId: string) => {
    e.preventDefault()
    if (!dragCounterRef.current[cellId]) {
      dragCounterRef.current[cellId] = 0
    }
    dragCounterRef.current[cellId]++
    setDragOverCell(cellId)
  }, [])

  const handleDragLeave = useCallback((e: React.DragEvent, cellId: string) => {
    e.preventDefault()
    if (dragCounterRef.current[cellId]) {
      dragCounterRef.current[cellId]--
    }
    if (dragCounterRef.current[cellId] <= 0) {
      dragCounterRef.current[cellId] = 0
      if (dragOverCell === cellId) {
        setDragOverCell(null)
      }
    }
  }, [dragOverCell])

  // Handle drop for daily view (changes time)
  const handleDropDaily = useCallback((e: React.DragEvent, timeSlot: string, staffId: number | string) => {
    e.preventDefault()
    setDragOverCell(null)
    dragCounterRef.current = {}

    if (!draggedAppointment) return

    // Don't do anything if dropped on same slot
    const currentHour = new Date(draggedAppointment.startTime)
    const userTZ = user?.timezone || 'UTC'
    const currentHourStr = new Intl.DateTimeFormat("en-US", {
      timeZone: userTZ,
      hour: "2-digit",
      hour12: false
    }).formatToParts(currentHour).find(p => p.type === "hour")?.value || "00"

    if (`${currentHourStr}:00` === timeSlot && draggedAppointment.staffId === staffId) {
      setDraggedAppointment(null)
      return
    }

    const newDate = formatLocalDate(date)
    const newTime = timeSlot

    setIsDroppingAppointment(true)

    modifyAppointmentMutation.mutate({
      bookingId: draggedAppointment.bookingId,
      date: newDate,
      time: newTime
    }, {
      onSuccess: (data) => {
        setIsDroppingAppointment(false)
        setDraggedAppointment(null)
        if (data?.suggestions) {
          // Slot not available - show toast
          toast.showError("The requested time slot is not available. Please try a different time.")
        } else {
          onAppointmentUpdate?.()
        }
      },
      onError: (error: any) => {
        setIsDroppingAppointment(false)
        setDraggedAppointment(null)
        const data = error.response?.data
        if (data?.reason === "SLOT_NOT_AVAILABLE") {
          toast.showError("The requested time slot is not available. Please try a different time.")
        }
      }
    })
  }, [draggedAppointment, date, modifyAppointmentMutation, onAppointmentUpdate, user?.timezone, toast])

  // Handle drop for weekly/monthly view (changes date)
  const handleDropWeeklyMonthly = useCallback((e: React.DragEvent, dayKey: string, staffId: number | string) => {
    e.preventDefault()
    setDragOverCell(null)
    dragCounterRef.current = {}

    if (!draggedAppointment) return

    // Don't do anything if dropped on same day
    if (draggedAppointment.dateKey === dayKey) {
      setDraggedAppointment(null)
      return
    }

    // Extract time from the original appointment
    const originalStart = new Date(draggedAppointment.startTime)
    const userTZ = user?.timezone || 'UTC'
    const timeParts = new Intl.DateTimeFormat("en-US", {
      timeZone: userTZ,
      hour: "2-digit",
      minute: "2-digit",
      hour12: false
    }).formatToParts(originalStart)

    const hour = timeParts.find(p => p.type === "hour")?.value || "00"
    const minute = timeParts.find(p => p.type === "minute")?.value || "00"
    const newTime = `${hour}:${minute}`

    setIsDroppingAppointment(true)

    modifyAppointmentMutation.mutate({
      bookingId: draggedAppointment.bookingId,
      date: dayKey,
      time: newTime
    }, {
      onSuccess: (data) => {
        setIsDroppingAppointment(false)
        setDraggedAppointment(null)
        if (data?.suggestions) {
          toast.showError("The requested slot is not available on this date. Please try a different date.")
        } else {
          onAppointmentUpdate?.()
        }
      },
      onError: (error: any) => {
        setIsDroppingAppointment(false)
        setDraggedAppointment(null)
        const data = error.response?.data
        if (data?.reason === "SLOT_NOT_AVAILABLE") {
          toast.showError("The requested slot is not available on this date. Please try a different date.")
        }
      }
    })
  }, [draggedAppointment, modifyAppointmentMutation, onAppointmentUpdate, user?.timezone, toast])

  // Check if an appointment is draggable
  const isDraggable = (appointment: Appointment) => {
    return appointment.status !== 'cancelled' &&
      (appointment.status === 'confirmed' || appointment.status === 'pending') &&
      new Date(appointment.startTime) > new Date()
  }

  // ===== SIDE DRAWER =====

  function SideDrawer() {
    return (
      <div className="relative z-100">
        <Sheet open={isDrawerOpen} onOpenChange={setIsDrawerOpen}>
          <SheetContent
            side="right"
            className="rounded-t-lg w-96 [&>button]:top-5 [&>button]:right-5 [&>button]:text-white [&>button]:hover:text-gray-200 [&>button>svg]:stroke-[4px] p-0 border-l-0 flex flex-col"
          >
            <SheetTitle className="sr-only">{drawerData.bookingType} {t("calendar.drawer.bookingDetails")}</SheetTitle>

            <div className="bg-primary-gradient px-6 py-4 rounded-t-lg">
              <div className="text-white">
                <div className="text-sm font-medium mb-2 capitalize">{drawerData.bookingType} {t("calendar.drawer.booking")}</div>

                <div className="flex items-center gap-3">
                  <Avatar className="w-10 h-10 rounded-full overflow-hidden">
                    <AvatarImage src={drawerData.staffAvatar} alt={drawerData.staffName} className="object-cover" />
                    <AvatarFallback className="rounded-full bg-gray-200 text-gray-600 text-xs">
                      {drawerData.staffName.charAt(0).toUpperCase()}
                    </AvatarFallback>
                  </Avatar>
                  <div>
                    <div className="text-lg font-medium">{drawerData.staffName}</div>
                    <div className="text-sm opacity-90">{drawerData.dayLabel}</div>
                  </div>
                </div>
              </div>
            </div>

            <div className="p-6 flex-1 overflow-y-auto">
              <div className="space-y-3">
                {drawerData.appointments.map(apt => (
                  <div key={apt.id} className="h-20 relative">
                    <AppointmentSlot
                      startTime={apt.startTime}
                      endTime={apt.endTime}
                      clientName={apt.clientName}
                      service={apt.service}
                      color={apt.color}
                      status={apt.status}
                      generatedBy={apt.generatedBy}
                      compact={true}
                      clientId={apt.clientId}
                      onClick={() => {
                        if (apt.clientId) {
                          router.push(`/dashboard/customers/${apt.clientId}/appointments`)
                        }
                      }}
                    />
                    {(apt.status === 'confirmed' || apt.status === 'pending') && new Date(apt.startTime) > new Date() && (
                      <div className="absolute top-2 right-2 flex gap-1">
                        <Button
                          size="sm"
                          variant="outline"
                          className="h-6 w-6 p-0 bg-white hover:bg-gray-50"
                          onClick={() => openUpdateModal(apt)}
                          disabled={cancellingAppointmentId === apt.id}
                        >
                          <Edit className="h-3 w-3" />
                        </Button>
                        <Button
                          size="sm"
                          variant="outline"
                          className="h-6 w-6 p-0 bg-white hover:bg-red-50 hover:border-red-300"
                          onClick={() => handleCancelAppointment(apt)}
                          disabled={cancellingAppointmentId === apt.id}
                        >
                          <Trash2 className="h-3 w-3 text-red-600" />
                        </Button>
                      </div>
                    )}
                  </div>
                ))}
              </div>
            </div>
          </SheetContent>
        </Sheet>
      </div>
    )
  }

  // ===== LOADING OVERLAY =====
  function DragDropLoadingOverlay() {
    if (!isDroppingAppointment) return null
    return (
      <div className="fixed inset-0 bg-black/20 backdrop-blur-[1px] z-[9999] flex items-center justify-center">
        <div className="bg-white rounded-xl shadow-2xl px-8 py-6 flex items-center gap-4">
          <Loader2 className="h-6 w-6 animate-spin text-blue-600" />
          <span className="text-base font-medium text-gray-800">Rescheduling appointment...</span>
        </div>
      </div>
    )
  }

  // ===== WEEKLY VIEW =====
  if (activeTab === "weekly") {
    const weekDays = getWeekDays(date)

    return (
      <>
        <DragDropLoadingOverlay />
        <div className="bg-white rounded-md flex flex-col h-full min-h-0">
          <div className="flex-1 overflow-auto min-h-0">
            <div className="inline-block min-w-0 align-top">
              <div
                className="grid gap-0 border-b border-[#DCDCDC] sticky top-0 z-30 bg-white shadow-md"
                style={{
                  gridTemplateColumns: `${rowHeaderWidth} repeat(${minStaffColumns}, ${columnWidth})`,
                  width: totalGridWidth
                }}
              >
                <div className="h-20 border-r border-[#DCDCDC] bg-white sticky left-0 z-40" style={{ width: rowHeaderWidth }}></div>
                {displayStaffMembers.map(staff => (
                  <div key={staff.id} className="flex items-center justify-center h-20 p-2 border-r border-[#DCDCDC] bg-white">
                    {staff.name ? (
                      <>
                        <Avatar className="w-10 h-10 sm:w-10 sm:h-10 rounded-full mr-2 shrink-0">
                          <AvatarImage src={staff.avatar} alt={staff.name} className="object-cover" />
                          <AvatarFallback className="rounded-full bg-gray-200 text-gray-600 text-xs">
                            {staff.name.charAt(0).toUpperCase()}
                          </AvatarFallback>
                        </Avatar>
                        <div className="flex flex-col min-w-0 flex-1">
                          <span className="text-xs font-medium text-black text-left truncate">{staff.name}</span>
                          {staff.title && <span className="text-xs text-gray-500 text-left truncate">{staff.title}</span>}
                        </div>
                      </>
                    ) : null}
                  </div>
                ))}
              </div>

              <div className="grid gap-0">
                {weekDays.map(day => {
                  const dayKey = formatLocalDate(day)

                  return (
                    <div
                      key={day.toISOString()}
                      className="grid border-b border-[#DCDCDC]"
                      style={{
                        gridTemplateColumns: `${rowHeaderWidth} repeat(${minStaffColumns}, ${columnWidth})`,
                        width: totalGridWidth
                      }}
                    >
                      <div
                        className={cn("flex items-center justify-center h-32 px-2 border-r border-[#DCDCDC] sticky left-0 z-20 shadow-sm", dayKey === todayKey ? "bg-red-600 text-white" : "bg-blue-900 text-white")}
                        style={{ width: rowHeaderWidth }}
                      >
                        <span className={cn("text-sm text-center", dayKey === todayKey ? "font-bold" : "font-medium")}>
                          {day.toLocaleDateString(locale, { weekday: 'short', month: 'short', day: 'numeric' })}
                        </span>
                      </div>

                      {displayStaffMembers.map(staff => {
                        if (!staff.name) {
                          return (
                            <div key={`${day.toISOString()}-${staff.id}`} className="h-32 p-2 border-r border-[#DCDCDC] bg-white" />
                          )
                        }

                        const cellId = `weekly-${dayKey}-${staff.id}`
                        const dayAppointments = allAppointments.filter(apt => {
                          return apt.staffId === staff.id && apt.dateKey === dayKey
                        })

                        const visibleAppointments = dayAppointments.slice(0, 1)
                        const remainingCount = dayAppointments.length - 1
                        const isDropTarget = dragOverCell === cellId && draggedAppointment !== null

                        return (
                          <div
                            key={`${day.toISOString()}-${staff.id}`}
                            className={cn(
                              "h-32 p-2 border-r border-[#DCDCDC] bg-white transition-all duration-200",
                              isDropTarget && "bg-blue-50 ring-2 ring-inset ring-blue-400 shadow-inner"
                            )}
                            onDragOver={handleDragOver}
                            onDragEnter={(e) => handleDragEnter(e, cellId)}
                            onDragLeave={(e) => handleDragLeave(e, cellId)}
                            onDrop={(e) => handleDropWeeklyMonthly(e, dayKey, staff.id)}
                          >
                            <div className="space-y-2">
                              {visibleAppointments.map(apt => (
                                <div
                                  key={apt.id}
                                  draggable={isDraggable(apt)}
                                  onDragStart={(e) => handleDragStart(e, apt)}
                                  onDragEnd={handleDragEnd}
                                  className={cn(
                                    "relative group",
                                    isDraggable(apt) && "cursor-grab active:cursor-grabbing",
                                    draggedAppointment?.id === apt.id && "opacity-40 scale-95"
                                  )}
                                >
                                  {isDraggable(apt) && (
                                    <div className="absolute -left-0.5 top-1/2 -translate-y-1/2 z-10 opacity-0 group-hover:opacity-60 transition-opacity">
                                      <GripVertical className="h-3.5 w-3.5 text-gray-500" />
                                    </div>
                                  )}
                                  <AppointmentSlot
                                    startTime={apt.startTime}
                                    endTime={apt.endTime}
                                    clientName={apt.clientName}
                                    service={apt.service}
                                    color={apt.color}
                                    status={apt.status}
                                    generatedBy={apt.generatedBy}
                                    clientId={apt.clientId}
                                    compact={true}
                                    onClick={() =>
                                      openDrawer([apt], staff.name, staff.avatar, day.toLocaleDateString(locale, { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }), "weekly")
                                    }
                                  />
                                </div>
                              ))}
                              {remainingCount > 0 && (
                                <button
                                  onClick={() =>
                                    openDrawer(dayAppointments, staff.name, staff.avatar, day.toLocaleDateString(locale, { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }), "weekly")
                                  }
                                  className="w-full text-center py-1 text-sm font-semibold text-blue-600 hover:bg-blue-50 rounded-md transition-colors"
                                >
                                  +{remainingCount} More
                                </button>
                              )}
                            </div>
                          </div>
                        )
                      })}
                    </div>
                  )
                })}
              </div>
            </div>
          </div>
        </div>

        <SideDrawer />

        <UpdateBookingModal
          open={isUpdateModalOpen}
          setOpen={setIsUpdateModalOpen}
          appointment={selectedAppointment}
          services={services}
          clients={clients}
          onSuccess={handleAppointmentUpdate}
        />
      </>
    )
  }

  // ===== MONTHLY VIEW =====
  if (activeTab === "monthly") {
    const monthDays = getMonthDays(date)

    return (
      <>
        <DragDropLoadingOverlay />
        <div className="bg-white rounded-md flex flex-col h-full min-h-0">
          <div className="flex-1 overflow-auto min-h-0">
            <div className="inline-block min-w-0 align-top">
              <div
                className="grid gap-0 border-b border-[#DCDCDC] sticky top-0 z-30 bg-white shadow-md"
                style={{
                  gridTemplateColumns: `${rowHeaderWidth} repeat(${minStaffColumns}, ${columnWidth})`,
                  width: totalGridWidth
                }}
              >
                <div className="h-20 border-r border-[#DCDCDC] bg-white sticky left-0 z-40" style={{ width: rowHeaderWidth }}></div>
                {displayStaffMembers.map(staff => (
                  <div key={staff.id} className="flex items-center justify-center h-20 p-2 border-r border-[#DCDCDC] bg-white">
                    {staff.name ? (
                      <>
                        <Avatar className="w-10 h-10 sm:w-10 sm:h-10 rounded-full mr-2 shrink-0">
                          <AvatarImage src={staff.avatar} alt={staff.name} className="object-cover" />
                          <AvatarFallback className="rounded-full bg-gray-200 text-gray-600 text-xs">
                            {staff.name.charAt(0).toUpperCase()}
                          </AvatarFallback>
                        </Avatar>
                        <div className="flex flex-col min-w-0 flex-1">
                          <span className="text-xs font-medium text-black text-left truncate">{staff.name}</span>
                          {staff.title && <span className="text-xs text-gray-500 text-left truncate">{staff.title}</span>}
                        </div>
                      </>
                    ) : null}
                  </div>
                ))}
              </div>

              <div className="grid gap-0">
                {monthDays.map(day => {
                  const dayKey = formatLocalDate(day)

                  return (
                    <div
                      key={day.toISOString()}
                      className="grid border-b border-[#DCDCDC]"
                      style={{
                        gridTemplateColumns: `${rowHeaderWidth} repeat(${minStaffColumns}, ${columnWidth})`,
                        width: totalGridWidth
                      }}
                    >
                      <div
                        className={cn("flex items-center justify-center h-32 px-2 border-r border-[#DCDCDC] sticky left-0 z-20 shadow-sm", dayKey === todayKey ? "bg-red-600 text-white" : "bg-blue-900 text-white")}
                        style={{ width: rowHeaderWidth }}
                      >
                        <span className={cn("text-sm text-center", dayKey === todayKey ? "font-bold" : "font-medium")}>
                          {day.toLocaleDateString(locale, { weekday: 'short', month: 'short', day: 'numeric' })}
                        </span>
                      </div>

                      {displayStaffMembers.map(staff => {
                        if (!staff.name) {
                          return (
                            <div key={`${day.toISOString()}-${staff.id}`} className="h-32 p-2 border-r border-[#DCDCDC] bg-white" />
                          )
                        }

                        const cellId = `monthly-${dayKey}-${staff.id}`
                        const dayAppointments = allAppointments.filter(apt => {
                          return apt.staffId === staff.id && apt.dateKey === dayKey
                        })

                        const visibleAppointments = dayAppointments.slice(0, 1)
                        const remainingCount = dayAppointments.length - 1
                        const isDropTarget = dragOverCell === cellId && draggedAppointment !== null

                        return (
                          <div
                            key={`${day.toISOString()}-${staff.id}`}
                            className={cn(
                              "h-32 p-2 border-r border-[#DCDCDC] bg-white transition-all duration-200",
                              isDropTarget && "bg-blue-50 ring-2 ring-inset ring-blue-400 shadow-inner"
                            )}
                            onDragOver={handleDragOver}
                            onDragEnter={(e) => handleDragEnter(e, cellId)}
                            onDragLeave={(e) => handleDragLeave(e, cellId)}
                            onDrop={(e) => handleDropWeeklyMonthly(e, dayKey, staff.id)}
                          >
                            <div className="space-y-2">
                              {visibleAppointments.map(apt => (
                                <div
                                  key={apt.id}
                                  draggable={isDraggable(apt)}
                                  onDragStart={(e) => handleDragStart(e, apt)}
                                  onDragEnd={handleDragEnd}
                                  className={cn(
                                    "relative group",
                                    isDraggable(apt) && "cursor-grab active:cursor-grabbing",
                                    draggedAppointment?.id === apt.id && "opacity-40 scale-95"
                                  )}
                                >
                                  {isDraggable(apt) && (
                                    <div className="absolute -left-0.5 top-1/2 -translate-y-1/2 z-10 opacity-0 group-hover:opacity-60 transition-opacity">
                                      <GripVertical className="h-3.5 w-3.5 text-gray-500" />
                                    </div>
                                  )}
                                  <AppointmentSlot
                                    startTime={apt.startTime}
                                    endTime={apt.endTime}
                                    clientName={apt.clientName}
                                    service={apt.service}
                                    color={apt.color}
                                    status={apt.status}
                                    generatedBy={apt.generatedBy}
                                    clientId={apt.clientId}
                                    compact={true}
                                    onClick={() =>
                                      openDrawer([apt], staff.name, staff.avatar, day.toLocaleDateString(locale, { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }), "monthly")
                                    }
                                  />
                                </div>
                              ))}
                              {remainingCount > 0 && (
                                <button
                                  onClick={() =>
                                    openDrawer(dayAppointments, staff.name, staff.avatar, day.toLocaleDateString(locale, { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }), "monthly")
                                  }
                                  className="w-full text-center py-1 text-sm font-semibold text-blue-600 hover:bg-blue-50 rounded-md transition-colors"
                                >
                                  +{remainingCount} More
                                </button>
                              )}
                            </div>
                          </div>
                        )
                      })}
                    </div>
                  )
                })}
              </div>
            </div>
          </div>
        </div>

        <SideDrawer />

        <UpdateBookingModal
          open={isUpdateModalOpen}
          setOpen={setIsUpdateModalOpen}
          appointment={selectedAppointment}
          services={services}
          clients={clients}
          onSuccess={handleAppointmentUpdate}
        />
      </>
    )
  }

  // ===== DEFAULT DAILY VIEW =====
  return (
    <>
      <DragDropLoadingOverlay />
      <div className="bg-white rounded-md flex flex-col h-full min-h-0">
        <div className="flex-1 overflow-auto min-h-0">
          <div className="inline-block min-w-0 align-top">
            <div
              className="grid gap-0 border-b border-[#DCDCDC] sticky top-0 z-30 bg-white shadow-md"
              style={{
                gridTemplateColumns: `${rowHeaderWidth} repeat(${minStaffColumns}, ${columnWidth})`,
                width: totalGridWidth
              }}
            >
              <div className="h-20 border-r border-[#DCDCDC] bg-white sticky left-0 z-40" style={{ width: rowHeaderWidth }}></div>

              {displayStaffMembers.map((staff) => (
                <div key={staff.id} className="flex items-center justify-center h-20 p-2 border-r border-[#DCDCDC] bg-white">
                  {staff.name ? (
                    <>
                      <Avatar className="w-10 h-10 sm:w-10 sm:h-10 rounded-full mr-2 shrink-0">
                        <AvatarImage src={staff.avatar} alt={staff.name} className="object-cover" />
                        <AvatarFallback className="rounded-full bg-gray-200 text-gray-600 text-xs">
                          {staff.name.charAt(0).toUpperCase()}
                        </AvatarFallback>
                      </Avatar>
                      <div className="flex flex-col min-w-0 flex-1">
                        <span className="text-xs font-medium text-black text-left truncate">{staff.name}</span>
                        {staff.title && <span className="text-xs text-gray-500 text-left truncate">{staff.title}</span>}
                      </div>
                    </>
                  ) : null}
                </div>
              ))}
            </div>

            <div className="grid gap-0">
              {allTimeSlots.map(timeSlot => (
                <div
                  key={timeSlot}
                  className="grid border-b border-[#DCDCDC]"
                  style={{
                    gridTemplateColumns: `${rowHeaderWidth} repeat(${minStaffColumns}, ${columnWidth})`,
                    width: totalGridWidth
                  }}
                >
                  <div
                    className="flex items-center justify-center h-20 px-2 border-r border-[#DCDCDC] bg-gray-50 sticky left-0 z-20 shadow-sm"
                    style={{ width: rowHeaderWidth }}
                  >
                    <span className="text-sm font-medium text-gray-700">{formatTimeTo24H(timeSlot)}</span>
                  </div>

                  {displayStaffMembers.map((staff) => {
                    if (!staff.name) {
                      return (
                        <div key={staff.id} className="h-20 p-1 border-r border-[#DCDCDC] bg-white" />
                      )
                    }

                    const cellId = `daily-${timeSlot}-${staff.id}`
                    const relevantAppointments = timeSlots[timeSlot]?.filter(apt => apt.staffId === staff.id) || []
                    const appointment = relevantAppointments[0]
                    const remainingCount = relevantAppointments.length - 1
                    const isDropTarget = dragOverCell === cellId && draggedAppointment !== null

                    return (
                      <div
                        key={staff.id}
                        className={cn(
                          "min-h-20 p-1 border-r border-[#DCDCDC] bg-white flex flex-col items-center justify-center transition-all duration-200 relative",
                          isDropTarget && "bg-blue-50 ring-2 ring-inset ring-blue-400 shadow-inner"
                        )}
                        onDragOver={handleDragOver}
                        onDragEnter={(e) => handleDragEnter(e, cellId)}
                        onDragLeave={(e) => handleDragLeave(e, cellId)}
                        onDrop={(e) => handleDropDaily(e, timeSlot, staff.id)}
                      >
                        {appointment && (
                          <div
                            className={cn(
                              "w-full relative group",
                              isDraggable(appointment) && "cursor-grab active:cursor-grabbing",
                              draggedAppointment?.id === appointment.id && "opacity-40 scale-95"
                            )}
                            draggable={isDraggable(appointment)}
                            onDragStart={(e) => handleDragStart(e, appointment)}
                            onDragEnd={handleDragEnd}
                          >
                            {isDraggable(appointment) && (
                              <div className="absolute -left-0.5 top-1/2 -translate-y-1/2 z-10 opacity-0 group-hover:opacity-60 transition-opacity">
                                <GripVertical className="h-3.5 w-3.5 text-gray-500" />
                              </div>
                            )}
                            <AppointmentSlot
                              startTime={appointment.startTime}
                              endTime={appointment.endTime}
                              clientName={appointment.clientName}
                              service={appointment.service}
                              color={appointment.color}
                              status={appointment.status}
                              generatedBy={appointment.generatedBy}
                              clientId={appointment.clientId}
                              compact={true}
                              onClick={() =>
                                openDrawer([appointment], staff.name, staff.avatar, formatter.dateTime(date, { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }), "daily")
                              }
                            />
                          </div>
                        )}
                        {remainingCount > 0 && (
                          <button
                            onClick={() =>
                              openDrawer(relevantAppointments, staff.name, staff.avatar, formatter.dateTime(date, { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }), "daily")
                            }
                            className="mt-1 w-full py-0.5 text-[10px] font-semibold text-blue-600 hover:bg-blue-50 rounded transition-colors whitespace-nowrap"
                          >
                            +{remainingCount} More
                          </button>
                        )}
                      </div>
                    )
                  })}
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>

      <SideDrawer />

      <UpdateBookingModal
        open={isUpdateModalOpen}
        setOpen={setIsUpdateModalOpen}
        appointment={selectedAppointment}
        services={services}
        clients={clients}
        onSuccess={handleAppointmentUpdate}
      />
    </>
  )
}
