"use client"

import type React from "react"
import { useEffect, useRef, useState, useMemo, useCallback } from "react"
import { format, addMinutes } from "date-fns"
import { fr } from "date-fns/locale"
import { Table, TableBody, TableCell, TableHead, TableRow, Typography, Box, IconButton, Input, CircularProgress } from "@mui/material"
import { styled } from "@mui/material/styles"
import { DndContext, DragOverlay, closestCenter, type DragEndEvent, type DragStartEvent } from "@dnd-kit/core"
import FontAwesome from "@/shared/components/fontawesome"
import { faCar, faUserTie, faXmark, faPhone, faAngleDoubleLeft, faAngleDoubleRight, faClock } from "@fortawesome/free-solid-svg-icons"
import { faOrcid } from "@fortawesome/free-brands-svg-icons"
import { StyledTableContainer } from "@/shared/theme/css"
import { LeaveType, ScheduleToolbar } from "@/shared/components/schedule/schedule-toolbar"
import { calculateTimeSlotWidth, groupOverlappingSlots, findSlotIndexInGroup, StatusColor, INTERVAL_MINUTES } from "./utils/schedule-utils"
import { DriverDetailsPopover } from "./components/driver-details-popover"
import { mainColor } from "@/shared/components/table/styles"
import { TrajetDetailsPopover } from "./components/trajet-details.popover"
import { DriverDraggableTimeSlot } from "./components/draggable-time-slot"
import { DroppableCell } from "./components/droppable-cell"
import { DRIVER_TABLE_COLUMNS } from "@/shared/_mock/_driverSchedule"
import { useTableManager, type TableConfig } from "@/hooks/use-table-manager"
import CustomDrawer from "@/shared/components/drawer/custom-drawer"
import { ModeType, TableType } from "@/shared/types/common"
import type { Dayjs } from "dayjs"
import type { TimeSlot, CurrentTimeSlot } from "../../planning/types/planning-types"
import { InterventionDetailsPopover } from "../../planning/components/intervention-details-popover"
import CustomTooltip from "@/shared/components/tooltips/tooltip-custom"
import ConditionalComponent from "@/shared/components/table/ConditionalComponent"
import ConfirmDialog from "@/shared/components/dialog/confirmDialog"
import { AbsenceBlock } from "./components/absence-block"
import { enqueueSnackbar } from "notistack"
import { CustomSlider } from "../../rh/calendar/styles/schedule-toolbar-styles"
import { useDriverStore } from "@/shared/api/stores/driverStore"
import { usePlanningDriverStore } from "@/shared/api/stores/planningDriverStore"
import { DraggableNonAffectedSlot } from "./components/draggable-non-affected-slot"
import type { Driver, ScheduleData, DriverTimeSlot, DriverAbsence } from "./types"
import { useDriverAbsenceStore } from "@/shared/api/stores/driverAbsenceStore"
import { useTripCircuitStore } from "@/shared/api/stores/circuit-service/tripCircuitStore"
import { TripCircuitDetails } from "@/shared/types/circuit"
import type { DurationFilter } from "@/shared/components/schedule/date-picker-popover"
import { faFilter } from "@fortawesome/free-solid-svg-icons"
import { IActivePlanningDriver } from "@/shared/types/driver"
import dayjs from "dayjs"
import SendDriverPlanningDialog from "@/shared/components/dialog/roadmap-planning-driver/send-roadmap-planning-dialog"
import TrajetPlanningForm from "./utils/planningTrajet/trajet-planning-form"

const CELL_WIDTH = 47.11111068725586
const SLOT_HEIGHT = 35
const LEFT_COLUMN_WIDTH = 152
const DRAWER_WIDTH = 650
const MIN_INTERVALE = ["00", "15", "30", "45"]
export default function DriverSchedule() {
  // State management
  const [selectedDate, setSelectedDate] = useState<Date>(new Date())
  const [zoomLevel, setZoomLevel] = useState(50)
  const [scheduleData, setScheduleData] = useState<ScheduleData>({} as ScheduleData)
  const [activeId, setActiveId] = useState<string | null>(null)
  const [leftColumnWidth, setLeftColumnWidth] = useState(LEFT_COLUMN_WIDTH)
  const [cellWidth, setCellWidth] = useState(CELL_WIDTH)
  const [isLoading, setIsLoading] = useState(true)
  const [openRoadmapDialog, setOpenRoadmapDialog] = useState(false)
  const [planningDriver, setPlanningDriver] = useState<IActivePlanningDriver>({
    id: 0,
    name: "",
    departmentId: 0,
    departmentName: "",
    planningDay: dayjs(),
  });


  // Drawer states
  const [isDrawerOpen, setIsDrawerOpen] = useState(false)
  const [isDrawerOpenPersonalized, setIsDrawerOpenPersonalized] = useState(false)
  const [isBottomDrawerOpen, setIsBottomDrawerOpen] = useState(false)
  const [drawerMode, setDrawerMode] = useState<ModeType>('view')

  // Data states
  const [driversList, setDriversList] = useState<Driver[]>([])
  const [driversListToDetails, setDriversListToDetails] = useState<Driver[]>([])
  const [driversLoaded, setDriversLoaded] = useState(false) // Add this flag
  const [planningSlots, setPlanningSlots] = useState<DriverTimeSlot[]>([])
  const [nonAffectedSlotsPrincipal, setNonAffectedSlotsPrincipal] = useState<DriverTimeSlot[]>([])
  const [nonAffectedSlotsSecondary, setNonAffectedSlotsSecondary] = useState<DriverTimeSlot[]>([])
  const [tripData, setTripData] = useState<TripCircuitDetails | null>(null)
  const [currentTimeSlot, setCurrentTimeSlot] = useState<CurrentTimeSlot>()
  // UI interaction states
  const [anchorEl, setAnchorEl] = useState<HTMLElement | null>(null)
  const [hoveredDriver, setHoveredDriver] = useState<Driver | null>(null)
  const [anchorElT, setAnchorElT] = useState<HTMLElement | null>(null)
  const [hoveredSlot, setHoveredSlot] = useState<DriverTimeSlot | TimeSlot | null>(null)
  const [driverQuery, setDriverQuery] = useState("")

  // Filter states
  const [isAbsenceFilterActive, setIsAbsenceFilterActive] = useState<boolean>(false)
  const [selectValue, setSelectValue] = useState<LeaveType>()

  // Add after other state declarations
  const [durationFilter, setDurationFilter] = useState<DurationFilter | null>(null)

  // Color intensity
  const [colorDegree, setColorDegree] = useState(() =>
    localStorage.getItem("colorDegree") ? parseInt(localStorage.getItem("colorDegree")!, 10) : 0
  )

  // Refs
  const headerCellRef = useRef<HTMLTableCellElement>(null)
  const minuteCellRef = useRef<HTMLTableCellElement>(null)

  // Dialog states
  const [confirmDialog, setConfirmDialog] = useState<{ open: boolean; slot: DriverTimeSlot | null }>({
    open: false,
    slot: null,
  })

  const [affectationDialog, setAffectationDialog] = useState<{
    open: boolean
    slot: DriverTimeSlot | null
    targetDriverId: string
    targetDriverName: string
    action: 'affect' | 'reaffect' | 'disaffect' | null
  }>({
    open: false,
    slot: null,
    targetDriverId: "",
    targetDriverName: "",
    action: null,
  })

  // Table configuration
  const driverConfig: TableConfig<Driver> = {
    type: "schedule",
    initialData: driversList,
    defaultTableHead: DRIVER_TABLE_COLUMNS,
  }

  const { filteredData, handleFilterChange, tableHead, handleResetFilters } = useTableManager<Driver>({
    ...driverConfig,
    defaultTableHead: DRIVER_TABLE_COLUMNS,
  })

  const { getTripCircuitById } = useTripCircuitStore()

  /**
 * Check if a driver is available (has no conflicts) during the filtered duration
 */
  const isDriverAvailableInDuration = useCallback((
    driverId: string,
    slots: DriverTimeSlot[],
    absences: DriverAbsence[],
    filter: DurationFilter
  ): boolean => {
    if (!filter.enabled) return true

    const filterStart = parseInt(filter.startHour) * 60 + parseInt(filter.startMinute)
    const filterEnd = parseInt(filter.endHour) * 60 + parseInt(filter.endMinute)

    const driverSlots = slots.filter(slot => slot.driverId === driverId)
    const driverAbsences = absences.filter(absence => absence.driverId === driverId)

    const hasConflictingSlot = driverSlots.some(slot => {
      const slotStart = parseInt(slot.pickupStartHeure) * 60 + parseInt(slot.pickupStartMinute)
      const slotEnd = parseInt(slot.returnEndHeure) * 60 + parseInt(slot.returnEndMinute)
      return slotStart < filterEnd && slotEnd > filterStart
    })

    const hasConflictingAbsence = driverAbsences.some(absence => {
      const absenceStart = parseInt(absence.startHeure) * 60 + parseInt(absence.startMinute)
      const absenceEnd = parseInt(absence.endHeure) * 60 + parseInt(absence.endMinute)
      return absenceStart < filterEnd && absenceEnd > filterStart
    })

    return !hasConflictingSlot && !hasConflictingAbsence
  }, [])



  const isSlotsInDuration = useCallback((
    slots: DriverTimeSlot[],
    filter: DurationFilter
  ): DriverTimeSlot[] => {
    if (!filter.enabled) return slots

    const filterStart = parseInt(filter.startHour) * 60 + parseInt(filter.startMinute)
    const filterEnd = parseInt(filter.endHour) * 60 + parseInt(filter.endMinute)

    return slots.filter(slot => {
      const slotStart = parseInt(slot.pickupStartHeure) * 60 + parseInt(slot.pickupStartMinute)
      const slotEnd = parseInt(slot.returnEndHeure) * 60 + parseInt(slot.returnEndMinute)

      // Check if slot overlaps with the duration
      return slotStart < filterEnd && slotEnd > filterStart
    })
  }, [])



  const handleDurationFilterChange = useCallback((filter: DurationFilter | null) => {
    setDurationFilter(filter)
  }, [])


  // Helper functions
  const normalizeTimeValue = (value: string | undefined): string => {
    if (!value) return "00"
    return value.toString().padStart(2, "0")
  }

  const normalizeSlots = (slots: DriverTimeSlot[]): DriverTimeSlot[] =>
    slots.map((slot) => {
      const hasDriver = slot.driverId !== null &&
        slot.driverId !== undefined &&
        slot.driverId !== "" &&
        String(slot.driverId).trim() !== ""

      return {
        ...slot,
        id: slot.isAssigned ? slot.id : `non-affected-${slot.id}`,
        isAssigned: slot.isAssigned,
        driverId: slot.driverId,
        startHeure: normalizeTimeValue(slot.startHeure),
        startMinute: normalizeTimeValue(slot.startMinute),
        endHeure: normalizeTimeValue(slot.endHeure),
        endMinute: normalizeTimeValue(slot.endMinute),
        pickupStartHeure: hasDriver ? normalizeTimeValue(slot.pickupStartHeure) : normalizeTimeValue(slot.startHeure),
        pickupStartMinute: hasDriver ? normalizeTimeValue(slot.pickupStartMinute) : normalizeTimeValue(slot.startMinute),
        returnEndHeure: hasDriver ? normalizeTimeValue(slot.returnEndHeure) : normalizeTimeValue(slot.endHeure),
        returnEndMinute: hasDriver ? normalizeTimeValue(slot.returnEndMinute) : normalizeTimeValue(slot.endMinute),
      }
    })

  const isSlotInCell = (
    slot: DriverTimeSlot | TimeSlot | DriverAbsence,
    hourHH: string,
    minuteMM: string
  ) => {
    const cellStart = parseInt(hourHH, 10) * 60 + parseInt(minuteMM, 10)
    const cellEnd = cellStart + INTERVAL_MINUTES

    const parseTime = (h: string | undefined, m: string | undefined) => {
      if (!h || !m) return null
      return parseInt(h, 10) * 60 + parseInt(m, 10)
    }

    const slotStart = "pickupStartHeure" in slot
      ? parseTime(slot.pickupStartHeure, slot.pickupStartMinute)
      : parseTime((slot as any).startHeure, (slot as any).startMinute)

    if (slotStart === null) return false
    return slotStart >= cellStart && slotStart < cellEnd
  }

  const calculateSlotLeftOffset = (
    slot: DriverTimeSlot,
    cellHour: string,
    cellMinute: string,
    cellWidth: number
  ) => {
    const cellStart = parseInt(cellHour, 10) * 60 + parseInt(cellMinute, 10)
    const slotStart = parseInt(slot.pickupStartHeure, 10) * 60 + parseInt(slot.pickupStartMinute, 10)
    const offsetMinutes = slotStart - cellStart
    return (offsetMinutes / INTERVAL_MINUTES) * cellWidth
  }

  const separateNonAffectedSlots = (nonAffectedNormalizedSlots: DriverTimeSlot[]) => {
    const isSlotOverlapping = (slot: DriverTimeSlot, principal: DriverTimeSlot): boolean => {
      const slotStart = parseInt(slot.startHeure) * 60 + parseInt(slot.startMinute)
      const slotEnd = parseInt(slot.endHeure) * 60 + parseInt(slot.endMinute)
      const principalStart = parseInt(principal.startHeure) * 60 + parseInt(principal.startMinute)
      const principalEnd = parseInt(principal.endHeure) * 60 + parseInt(principal.endMinute)
      return slotStart < principalEnd && slotEnd > principalStart
    }

    const newPrincipalSlots: DriverTimeSlot[] = []
    const usedSlotIds = new Set<string>()

    const sortedSlots = [...nonAffectedNormalizedSlots].sort((a, b) => {
      const aStart = parseInt(a.startHeure) * 60 + parseInt(a.startMinute)
      const bStart = parseInt(b.startHeure) * 60 + parseInt(b.startMinute)
      return aStart - bStart
    })

    sortedSlots.forEach((slot) => {
      let foundOverlap = false

      for (let i = 0; i < newPrincipalSlots.length; i++) {
        if (isSlotOverlapping(slot, newPrincipalSlots[i])) {
          foundOverlap = true
          break
        }
      }

      if (!foundOverlap) {
        newPrincipalSlots.push(slot)
        usedSlotIds.add(slot.id)
      }
    })

    const newSecondarySlots = nonAffectedNormalizedSlots.filter(
      slot => !usedSlotIds.has(slot.id)
    )

    return { newPrincipalSlots, newSecondarySlots }
  }

  const getHourIntervals = () => {
    const intervals = []
    let currentTime = new Date(selectedDate)
    currentTime.setHours(0, 0, 0)
    for (let i = 0; i < 24; i++) {
      intervals.push({
        hour: format(currentTime, "HH"),
        startCell: i * 4,
        endCell: (i + 1) * 4 - 1,
      })
      currentTime = addMinutes(currentTime, 60)
    }
    return intervals
  }

  // Effects
  useEffect(() => {
    setIsAbsenceFilterActive(selectValue === "absence")
  }, [selectValue])

  useEffect(() => {
    localStorage.setItem("colorDegree", colorDegree.toString())
  }, [colorDegree])

  // Fetch drivers only once on mount
  useEffect(() => {
    const fetchDrivers = async () => {
      if (driversLoaded) return // Skip if already loaded

      try {
        const drivers = await useDriverStore.getState().getPlanningDrivers()
        setDriversList(drivers)
        setDriversListToDetails(drivers)
        setDriversLoaded(true)
      } catch (error) {
        console.error("Error fetching drivers:", error)
      }
    }

    fetchDrivers()
  }, [driversLoaded])

  // Fetch slots when date changes
  useEffect(() => {
    const fetchSlots = async () => {
      if (!driversLoaded) return // Wait for drivers to load first

      setIsLoading(true)
      try {
        const slots = await usePlanningDriverStore.getState().fetchDailySchedule(selectedDate.toISOString().split("T")[0])
        const absences = await useDriverAbsenceStore.getState().findAbsencesForDriverPlanning(selectedDate.toISOString().split("T")[0])

        absences.forEach((absence) => {
          absence.startHeure = "00"
          absence.startMinute = "00"
          absence.endHeure = "23"
          absence.endMinute = "45"
        })

        const normalizedSlots = normalizeSlots(slots)
        const nonAffectedNormalizedSlots = normalizeSlots(
          await usePlanningDriverStore.getState().fetchDailyNonAffected(selectedDate.toISOString().split("T")[0])
        )

        const { newPrincipalSlots, newSecondarySlots } = separateNonAffectedSlots(nonAffectedNormalizedSlots)

        setNonAffectedSlotsPrincipal(newPrincipalSlots)
        setNonAffectedSlotsSecondary(newSecondarySlots)
        setScheduleData((prev) => ({
          ...prev,
          drivers: driversList,
          timeSlots: normalizedSlots,
          absences: absences
        }))
        setPlanningSlots(normalizedSlots)
      } catch (error) {
        console.error("Error fetching slots:", error)
      } finally {
        setIsLoading(false)
      }
    }

    fetchSlots()
  }, [selectedDate, driversLoaded, driversList])

  useEffect(() => {
    if (minuteCellRef.current) {
      setCellWidth(minuteCellRef.current.getBoundingClientRect().width);
    }
    if (headerCellRef.current) {
      setLeftColumnWidth(headerCellRef.current.getBoundingClientRect().width);
    }
  }, [zoomLevel]);

  // Event handlers
  const handleDateChange = (date: Dayjs | Date) => {
    setSelectedDate(date instanceof Date ? date : date.toDate())
  }

  const handleZoomChange = (zoom: number) => {
    setZoomLevel(zoom)
  }

  const openPersonalizedPopUp = async (slot: DriverTimeSlot) => {
    setCurrentTimeSlot({
      date: slot.date,
      startHour: slot.startHeure,
      startMinute: slot.startMinute,
    });
    try {
      const trajectValue = await getTripCircuitById(slot.trajet)
      setTripData(trajectValue)

      if (!confirmDialog.open && !affectationDialog.open) {
        setDrawerMode("copy")
        setIsDrawerOpenPersonalized(true)
      }
    } catch (error) {
      console.error('Error fetching trip circuit:', error)
    }
  }

  const handleTimeSlotDoubleClick = async (slot: DriverTimeSlot) => {
    setCurrentTimeSlot({
      date: slot.date,
      startHour: slot.startHeure,
      startMinute: slot.startMinute,
    });
    try {
      const trajectValue = await getTripCircuitById(slot.trajet)
      setTripData(trajectValue)

      if (!confirmDialog.open && !affectationDialog.open) {
        setDrawerMode("view")
        setIsDrawerOpen(true)
      }
    } catch (error) {
      console.error('Error fetching trip circuit:', error)
    }
  }

  const handlePopoverOpenT = useCallback((event: React.MouseEvent<HTMLElement>, slot: DriverTimeSlot | TimeSlot) => {
    event.stopPropagation()
    setAnchorElT(event.currentTarget)
    setHoveredSlot(slot)
  }, [])

  const handlePopoverCloseT = useCallback(() => {
    setAnchorElT(null)
    setHoveredSlot(null)
  }, [])

  const handlePopoverOpen = useCallback((event: React.MouseEvent<HTMLElement>, driver: Driver) => {
    if (driver.id !== "") {
      event.preventDefault()
      event.stopPropagation()
      setAnchorEl(event.currentTarget)
      setHoveredDriver(driver)
    }
  }, [])

  const handlePopoverClose = useCallback(() => {
    setAnchorEl(null)
    setHoveredDriver(null)
  }, [])

  const handleDragStart = useCallback((event: DragStartEvent) => {
    setActiveId(event.active.id as string)
    // Disable popovers during drag for better performance
    if (anchorElT) handlePopoverCloseT()
    if (anchorEl) handlePopoverClose()
  }, [anchorElT, anchorEl, handlePopoverCloseT, handlePopoverClose])

  const updateSlotsLocally = (updatedSlot: DriverTimeSlot, operation: 'affect' | 'reaffect' | 'disaffect', helperId?: string) => {
    switch (operation) {
      case 'affect':
        setPlanningSlots(prev => [...prev, updatedSlot])

        if (helperId) {
          setNonAffectedSlotsPrincipal(prev =>
            prev.filter(slot => slot.id.replace('non-affected-', '') !== helperId)
          )
          setNonAffectedSlotsSecondary(prev =>
            prev.filter(slot => slot.id.replace('non-affected-', '') !== helperId)
          )
        }
        break

      case 'reaffect':
        // Update existing slot
        setPlanningSlots(prev => prev.map(slot =>
          slot.id === updatedSlot.id ? updatedSlot : slot
        ))
        break

      case 'disaffect':
        // Remove from planning slots
        setPlanningSlots(prev => prev.filter(slot => slot.id !== helperId))

        // Create normalized slot for non-affected list
        const normalizedSlot: DriverTimeSlot = {
          ...updatedSlot,
          id: `non-affected-${updatedSlot.id}`,
          driverId: "",
          isAssigned: false
        }

        // Check if it should go to principal or secondary based on overlap
        const overlapsWithPrincipal = nonAffectedSlotsPrincipal.some(slot => {
          const slotStart = parseInt(normalizedSlot.startHeure) * 60 + parseInt(normalizedSlot.startMinute)
          const slotEnd = parseInt(normalizedSlot.endHeure) * 60 + parseInt(normalizedSlot.endMinute)
          const principalStart = parseInt(slot.startHeure) * 60 + parseInt(slot.startMinute)
          const principalEnd = parseInt(slot.endHeure) * 60 + parseInt(slot.endMinute)
          return slotStart < principalEnd && slotEnd > principalStart
        })

        if (overlapsWithPrincipal) {
          setNonAffectedSlotsSecondary(prev => [...prev, normalizedSlot])
        } else {
          setNonAffectedSlotsPrincipal(prev => [...prev, normalizedSlot])
        }
        break
    }

    // Update schedule data
    setScheduleData(prev => ({
      ...prev,
      timeSlots: operation === 'disaffect'
        ? prev.timeSlots.filter(slot => slot.id !== helperId)
        : operation === 'affect'
          ? [...prev.timeSlots, updatedSlot]
          : prev.timeSlots.map(slot => slot.id === helperId ? updatedSlot : slot)
    }))
  }

  const AffectTrip = async (timeSlot: DriverTimeSlot & { isFromSidebar?: boolean }, targetId: string) => {
    const targetDriverNumber: number = parseInt(targetId.split('-')[1])

    const rawSlotId = timeSlot.id.startsWith("non-affected-")
      ? timeSlot.id.replace("non-affected-", "")
      : timeSlot.id

    try {
      const result = await usePlanningDriverStore.getState().AffectTrip(rawSlotId, targetDriverNumber)
      if (result && result.status === 'success' && result.data) {
        const normalizedSlot = normalizeSlots([result.data])[0]
        updateSlotsLocally(normalizedSlot, 'affect', rawSlotId)
        enqueueSnackbar('Trajet affecté avec succès', { variant: "success" })
      }
    } catch (error: any) {
      enqueueSnackbar(error?.message || 'Failed to affect trip', { variant: "error" })
    }
  }

  const reAffectTrip = async (timeSlot: DriverTimeSlot & { isFromSidebar?: boolean }, targetId: string) => {
    const targetDriverNumber: number = parseInt(targetId.split('-')[1])
    try {
      const result = await usePlanningDriverStore.getState().reAffectTrip(timeSlot.id, targetDriverNumber)
      if (result && result.status === 'success' && result.data) {
        const normalizedSlot = normalizeSlots([result.data])[0]
        updateSlotsLocally(normalizedSlot, 'reaffect')
        enqueueSnackbar('Trajet réaffecté avec succès', { variant: "success" })
      }
    } catch (error: any) {
      enqueueSnackbar(error?.message || 'Failed to reaffect trip', { variant: "error" })
    }
  }

  const disAffectTrip = async (driverId: string, slotId: string) => {
    try {
      const result = await usePlanningDriverStore.getState().disAffectTrip(slotId, driverId)
      if (result && result.status === 'success' && result.data) {
        const normalizedSlot = normalizeSlots([result.data])[0]
        updateSlotsLocally(normalizedSlot, 'disaffect', slotId)
        enqueueSnackbar('Trajet désaffecté avec succès', { variant: "success" })
      }
    } catch (error: any) {
      enqueueSnackbar(error?.message || 'Failed to disaffect trip', { variant: "error" })
    }
  }

  const handleDisaffectSlot = (driverId: string, slotId: string) => {
    const slot = planningSlots.find(s => s.id === slotId)
    if (slot) {
      setAffectationDialog({
        open: true,
        slot,
        targetDriverId: "",
        targetDriverName: "",
        action: 'disaffect'
      })
    }
  }

  const handleDragEnd = (event: DragEndEvent) => {
    const { active, over } = event

    if (!over || !active.data.current) {
      setActiveId(null)
      return
    }

    const timeSlot = active.data.current as DriverTimeSlot & { isFromSidebar?: boolean }
    const overId = over.id as string

    // Extract the raw slot ID (remove "non-affected-" prefix if present)
    const rawSlotId = timeSlot.id.startsWith("non-affected-")
      ? timeSlot.id.replace("non-affected-", "")
      : timeSlot.id

    // Check if dropped on sidebar OR "Non Affecté" row
    if (overId === "sidebar" || overId.startsWith("driver-")) {
      const targetDriverId = overId.startsWith("driver-") ? overId.split('-')[1] : null

      // If dropped on "Non Affecté" row (empty driver ID) or sidebar
      if (targetDriverId === "" || overId === "sidebar") {
        // Only disaffect if the slot currently has a driver
        if (timeSlot.driverId !== null && timeSlot.driverId !== "") {
          setAffectationDialog({
            open: true,
            slot: { ...timeSlot, id: rawSlotId },
            targetDriverId: "",
            targetDriverName: "",
            action: 'disaffect'
          })
        }
        setActiveId(null)
        return
      }
    }

    // Normal affectation/reaffectation logic
    const isNonAffected = timeSlot.driverId === null || timeSlot.driverId === ""

    try {
      const newTargetDriverId = overId.split('-')[1]
      const targetDriver = driversList.find((d) => d.id === newTargetDriverId)

      // Validate target driver exists and is not empty
      if (!targetDriver || newTargetDriverId === "") {
        setActiveId(null)
        return
      }

      const slotStart = parseInt(timeSlot.pickupStartHeure) * 60 + parseInt(timeSlot.pickupStartMinute)
      const slotEnd = parseInt(timeSlot.returnEndHeure) * 60 + parseInt(timeSlot.returnEndMinute)

      const targetDriverSlots = planningSlots.filter(
        (slot) => slot.driverId === newTargetDriverId &&
          slot.date === timeSlot.date &&
          slot.id !== timeSlot.id &&
          slot.id !== rawSlotId
      )

      const hasOverlap = targetDriverSlots.some((existingSlot) => {
        const existingStart = parseInt(existingSlot.pickupStartHeure) * 60 + parseInt(existingSlot.pickupStartMinute)
        const existingEnd = parseInt(existingSlot.returnEndHeure) * 60 + parseInt(existingSlot.returnEndMinute)
        return slotStart < existingEnd && slotEnd > existingStart
      })

      if (hasOverlap) {
        enqueueSnackbar("Le chauffeur a déjà un créneau qui chevauche cet intervalle", { variant: "warning" })
        setActiveId(null)
        return
      }

      setAffectationDialog({
        open: true,
        slot: { ...timeSlot, id: rawSlotId },
        targetDriverId: overId,
        targetDriverName: targetDriver.name,
        action: isNonAffected ? 'affect' : 'reaffect'
      })

    } catch (error) {
      console.error('Error in handleDragEnd:', error)
      enqueueSnackbar("Une erreur est survenue lors de l'affectation", { variant: "error" })
    } finally {
      setActiveId(null)
    }
  }

  const handleConfirmAffectation = async () => {
    if (!affectationDialog.slot || !affectationDialog.action) return

    if (affectationDialog.action === 'affect') {
      await AffectTrip(affectationDialog.slot, affectationDialog.targetDriverId)
    } else if (affectationDialog.action === 'reaffect') {
      await reAffectTrip(affectationDialog.slot, affectationDialog.targetDriverId)
    } else if (affectationDialog.action === 'disaffect') {
      await disAffectTrip(affectationDialog.slot.driverId!, affectationDialog.slot.id)
    }

    setAffectationDialog({ open: false, slot: null, targetDriverId: "", targetDriverName: "", action: null })
  }

  const handleCancelAffectation = () => {
    setAffectationDialog({ open: false, slot: null, targetDriverId: "", targetDriverName: "", action: null })
  }

  const filteredDrivers: Driver[] = useMemo(() => {
    let drivers = filteredData.filter((driver) =>
      !driverQuery || driver.name.toLowerCase().includes(driverQuery.toLowerCase())
    )

    // Apply duration filter based on THREE modes
    if (durationFilter && (durationFilter.startHour !== "" && durationFilter.endHour !== "")) {
      const filterStart = parseInt(durationFilter.startHour) * 60 + parseInt(durationFilter.startMinute)
      const filterEnd = parseInt(durationFilter.endHour) * 60 + parseInt(durationFilter.endMinute)

      if (durationFilter.enabled) {
        // MODE 1: Filter ENABLED - Use filterMode (drivers or slots)
        if (durationFilter.filterMode === 'drivers') {
          // DRIVER MODE: Show only available drivers (no conflicts)
          drivers = drivers.filter(driver => {
            if (driver.id === "") return true // Always show "Non Affecté"

            return isDriverAvailableInDuration(
              driver.id,
              planningSlots,
              scheduleData.absences || [],
              durationFilter
            )
          })
        } else if (durationFilter.filterMode === 'slots') {
          // SLOTS MODE: Show drivers who have slots in the duration
          const driversWithSlotsInDuration = new Set<string>()

          const slotsInDuration = isSlotsInDuration(planningSlots, durationFilter)
          slotsInDuration.forEach(slot => {
            if (slot.driverId) {
              driversWithSlotsInDuration.add(slot.driverId)
            }
          })

          drivers = drivers.filter(driver =>
            driver.id === "" || driversWithSlotsInDuration.has(driver.id)
          )
        }
      } else {
        // MODE 2: Filter DISABLED - Show drivers with slots in time range (same as slots mode but without checkbox)
        const driversWithSlotsInRange = new Set<string>()

        planningSlots.forEach(slot => {
          const slotStart = parseInt(slot.pickupStartHeure) * 60 + parseInt(slot.pickupStartMinute)
          const slotEnd = parseInt(slot.returnEndHeure) * 60 + parseInt(slot.returnEndMinute)

          // Check if slot overlaps with the time range
          if (slotStart < filterEnd && slotEnd > filterStart) {
            if (slot.driverId) {
              driversWithSlotsInRange.add(slot.driverId)
            }
          }
        })

        // Also check non-affected slots
        const allNonAffected = [...nonAffectedSlotsPrincipal, ...nonAffectedSlotsSecondary]
        const hasNonAffectedInRange = allNonAffected.some(slot => {
          const slotStart = parseInt(slot.startHeure) * 60 + parseInt(slot.startMinute)
          const slotEnd = parseInt(slot.endHeure) * 60 + parseInt(slot.endMinute)
          return slotStart < filterEnd && slotEnd > filterStart
        })

        drivers = drivers.filter(driver =>
          driver.id === "" ? hasNonAffectedInRange : driversWithSlotsInRange.has(driver.id)
        )
      }
    }

    return drivers
  }, [
    filteredData,
    driverQuery,
    durationFilter,
    planningSlots,
    scheduleData.absences,
    isDriverAvailableInDuration,
    isSlotsInDuration,
    nonAffectedSlotsPrincipal,
    nonAffectedSlotsSecondary
  ])

  const hourIntervals = useMemo(() => {
    return getHourIntervals()
  }, [selectedDate])

  const renderSidebarContent = () => (
    <Box sx={{ flex: 1, display: "flex", flexDirection: "column" }}>
      <Box sx={{ flex: 1, p: 3, overflow: "auto", backgroundColor: "background.default", height: "100%" }}>
        <Typography variant="h6" sx={{ mb: 2, color: "primary.main", fontWeight: 600 }}>
          <IconButton
            onClick={() => setIsBottomDrawerOpen(false)}
            sx={{
              backgroundColor: "primary.main",
              color: "primary.contrastText",
              ":hover": { backgroundColor: "primary.dark" },
              height: 30,
              width: 30,
              mr: 2
            }}
          >
            <FontAwesome sx={{ color: "primary.contrastText" }} width={18} icon={faAngleDoubleRight} />
          </IconButton>
          Non Affectés
        </Typography>
        <Typography variant="body2" sx={{ mb: 3, color: "text.secondary" }}>
          Glissez les créneaux vers les chauffeurs pour les affecter
        </Typography>
        {isLoading ? (
          <Box sx={{ display: "flex", justifyContent: "center", alignItems: "center", p: 4 }}>
            <CircularProgress />
          </Box>
        ) : (
          <Box sx={{ display: "flex", flexDirection: "column", gap: 1.5, mt: 2 }}>
            {nonAffectedSlotsSecondary
              .filter((slot) => slot.driverId === null)
              .map((slot) => (
                <DraggableNonAffectedSlot
                  key={slot.id}
                  slot={slot}
                  colorDegree={colorDegree}
                  onMouseEnter={handlePopoverOpenT}
                  onMouseLeave={handlePopoverCloseT}
                  onDoubleClick={() => handleTimeSlotDoubleClick(slot)}
                  onCopySlot={() => { }}
                />
              ))}
            {nonAffectedSlotsSecondary.filter((slot) => slot.driverId === null).length === 0 && (
              <Box
                sx={{
                  p: 4,
                  textAlign: "center",
                  color: "text.secondary",
                  backgroundColor: "grey.50",
                  borderRadius: 2,
                  border: "2px dashed",
                  borderColor: "grey.300",
                  mt: 4,
                }}
              >
                <FontAwesome icon={faXmark} sx={{ fontSize: 32, mb: 2, opacity: 0.5 }} />
                <Typography variant="body2">Aucun créneau non affecté</Typography>
              </Box>
            )}
          </Box>
        )}
      </Box>
    </Box>
  )

  return (
    <Box sx={{ display: "flex", flexDirection: "column", height: "100vh", overflow: "hidden" }}>
      <DndContext onDragStart={handleDragStart} onDragEnd={handleDragEnd} collisionDetection={closestCenter}>
        <Box
          sx={{
            width: isDrawerOpen || isBottomDrawerOpen ? `calc(100% - ${DRAWER_WIDTH}px)` : undefined,
            flex: 1,
            overflow: "hidden",
            transition: "width 0.3s ease-in-out",
          }}
        >
          <Box sx={{ ml: `${leftColumnWidth}px` }}>
            <Box sx={{ ml: `${leftColumnWidth}px` }}>
              <Box
                sx={{
                  display: 'flex',
                  flexWrap: 'wrap',
                  alignItems: 'center',
                  justifyContent: 'center',
                  gap: 2,
                  width: '100%',
                }}
              >
                <Box sx={{ flexShrink: 0 }}>
                  <IntensitySlider
                    colorDegrees={colorDegree}
                    setColorDegree={setColorDegree}
                  />
                </Box>
                <Box sx={{ flex: '0 1 auto', minWidth: 300 }}>
                  <ScheduleToolbar
                    date={selectedDate}
                    onDateChange={handleDateChange}
                    onDurationFilterChange={handleDurationFilterChange}
                    onZoomChange={handleZoomChange}
                    onResetFilters={handleResetFilters}
                    onFilters={handleFilterChange}
                    initialColumns={DRIVER_TABLE_COLUMNS}
                    onSelectType={(value) => setSelectValue(value)}
                    customAction={
                      <CustomTooltip title={"Consulter liste des Trajets non Affectés"} arrow>
                        <IconButton
                          disabled={isBottomDrawerOpen || nonAffectedSlotsSecondary.length <= 0}
                          sx={{
                            backgroundColor: "primary.main",
                            color: "primary.contrastText",
                            ":hover": { backgroundColor: "primary.dark" },
                            height: 30,
                            width: 30,
                          }}
                          onClick={() => setIsBottomDrawerOpen(true)}
                        >
                          <FontAwesome width={18} icon={faAngleDoubleLeft} />
                        </IconButton>
                      </CustomTooltip>
                    }
                    type={TableType.Driver}
                  />
                </Box>


              </Box>

              <ConditionalComponent
                isValid={!!durationFilter && durationFilter.startHour !== "" && durationFilter.endHour !== ""}
              >
                <Box
                  sx={{
                    mt: 1,
                    p: 1.5,
                    backgroundColor: durationFilter?.enabled
                      ? (durationFilter.filterMode === 'drivers' ? 'primary.lighter' : 'info.lighter')
                      : 'success.lighter',
                    borderRadius: 2,
                    border: '1px solid',
                    borderColor: durationFilter?.enabled
                      ? (durationFilter.filterMode === 'drivers' ? 'primary.main' : 'info.main')
                      : 'success.main',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'space-between',
                    maxWidth: 450,
                    mx: 'auto'
                  }}
                >
                  <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                    <FontAwesome
                      icon={
                        !durationFilter?.enabled
                          ? faClock
                          : durationFilter.filterMode === 'drivers'
                            ? faUserTie
                            : faClock
                      }
                      width={14}
                      color={
                        durationFilter?.enabled
                          ? (durationFilter.filterMode === 'drivers' ? 'primary.main' : 'info.main')
                          : 'success.main'
                      }
                    />
                    <Typography
                      variant="body2"
                      fontWeight={600}
                      color={
                        durationFilter?.enabled
                          ? (durationFilter.filterMode === 'drivers' ? 'primary.main' : 'info.main')
                          : 'success.main'
                      }
                    >
                      {!durationFilter?.enabled
                        ? `Affichage trajets: ${durationFilter?.startHour}:${durationFilter?.startMinute} → ${durationFilter?.endHour}:${durationFilter?.endMinute}`
                        : durationFilter.filterMode === 'drivers'
                          ? `Chauffeurs disponibles: ${durationFilter?.startHour}:${durationFilter?.startMinute} → ${durationFilter?.endHour}:${durationFilter?.endMinute}`
                          : `Trajets dans: ${durationFilter?.startHour}:${durationFilter?.startMinute} → ${durationFilter?.endHour}:${durationFilter?.endMinute}`
                      }
                    </Typography>
                  </Box>

                  <IconButton
                    size="small"
                    onClick={() => setDurationFilter(null)}
                    sx={{
                      width: 24,
                      height: 24,
                      color: durationFilter?.enabled
                        ? (durationFilter.filterMode === 'drivers' ? 'primary.main' : 'info.main')
                        : 'success.main',
                      '&:hover': {
                        backgroundColor: durationFilter?.enabled
                          ? (durationFilter.filterMode === 'drivers' ? 'primary.main' : 'info.main')
                          : 'success.main',
                        color: 'primary.contrastText'
                      }
                    }}
                  >
                    <FontAwesome icon={faXmark} width={12} />
                  </IconButton>
                </Box>
              </ConditionalComponent>

            </Box>

            <ConditionalComponent
              isValid={!!durationFilter && durationFilter.startHour !== "" && durationFilter.endHour !== ""}
            >
              <Box
                sx={{
                  mt: 1,
                  p: 1.5,
                  backgroundColor: durationFilter?.enabled
                    ? (durationFilter.filterMode === 'drivers' ? 'primary.lighter' : 'info.lighter')
                    : 'success.lighter',
                  borderRadius: 2,
                  border: '1px solid',
                  borderColor: durationFilter?.enabled
                    ? (durationFilter.filterMode === 'drivers' ? 'primary.main' : 'info.main')
                    : 'success.main',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'space-between',
                  maxWidth: 450
                }}
              >
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                  <FontAwesome
                    icon={
                      !durationFilter?.enabled
                        ? faClock
                        : durationFilter.filterMode === 'drivers'
                          ? faUserTie
                          : faClock
                    }
                    width={14}
                    color={
                      durationFilter?.enabled
                        ? (durationFilter.filterMode === 'drivers' ? 'primary.main' : 'info.main')
                        : 'success.main'
                    }
                  />
                  <Typography
                    variant="body2"
                    fontWeight={600}
                    color={
                      durationFilter?.enabled
                        ? (durationFilter.filterMode === 'drivers' ? 'primary.main' : 'info.main')
                        : 'success.main'
                    }
                  >
                    {!durationFilter?.enabled
                      ? `Affichage trajets: ${durationFilter?.startHour}:${durationFilter?.startMinute} → ${durationFilter?.endHour}:${durationFilter?.endMinute}`
                      : durationFilter.filterMode === 'drivers'
                        ? `Chauffeurs disponibles: ${durationFilter?.startHour}:${durationFilter?.startMinute} → ${durationFilter?.endHour}:${durationFilter?.endMinute}`
                        : `Trajets dans: ${durationFilter?.startHour}:${durationFilter?.startMinute} → ${durationFilter?.endHour}:${durationFilter?.endMinute}`
                    }
                  </Typography>
                </Box>

                <IconButton
                  size="small"
                  onClick={() => setDurationFilter(null)}
                  sx={{
                    width: 24,
                    height: 24,
                    color: durationFilter?.enabled
                      ? (durationFilter.filterMode === 'drivers' ? 'primary.main' : 'info.main')
                      : 'success.main',
                    '&:hover': {
                      backgroundColor: durationFilter?.enabled
                        ? (durationFilter.filterMode === 'drivers' ? 'primary.main' : 'info.main')
                        : 'success.main',
                      color: 'primary.contrastText'
                    }
                  }}
                >
                  <FontAwesome icon={faXmark} width={12} />
                </IconButton>
              </Box>
            </ConditionalComponent>

          </Box>

          <Box
            sx={{
              mt: 2,
              ml: `${leftColumnWidth}px`,
              py: 1,
              borderTopLeftRadius: 16,
              borderTopRightRadius: 16,
              display: "flex",
              fontWeight: 500,
              justifyContent: "center",
              backgroundColor: "white",
            }}
          >
            {format(selectedDate, "EEEE dd/MM/yyyy", { locale: fr })}
          </Box>

          {isLoading ? (
            <Box
              sx={{
                position: "absolute",
                top: "50%",
                left: "50%",
                transform: "translate(-50%, -50%)",
                display: "flex",
                justifyContent: "center",
                alignItems: "center",
                zIndex: 1000,
              }}
            >
              <CircularProgress />
            </Box>
          ) : (
            <Box sx={{ position: "relative" }}>
              <Box
                sx={{
                  position: "absolute",
                  top: 20,
                  left: 8,
                  zIndex: 5,
                  display: "flex",
                  alignItems: "center",
                  gap: 1,
                  backgroundColor: "primary.lighter",
                  px: 2,
                  py: 0.5,
                }}
              >
                <FontAwesome icon={faUserTie} color="primary.main" width={14} />
                <Typography variant="body2" fontWeight={600} color="primary.main">
                  Total: {filteredDrivers.length}
                </Typography>
              </Box>
              <StyledTableContainer sx={{ maxHeight: "calc(100vh - 200px)" }}>
                <Table stickyHeader size="small">
                  <TableHead>
                    <TableRow>
                      <HeaderCell
                        ref={headerCellRef}
                        sx={{
                          position: "sticky",
                          zIndex: 3,
                          left: 0,
                          backgroundColor: "primary.lighter",
                          border: "none",
                          width: leftColumnWidth,
                          minWidth: leftColumnWidth,
                        }}
                        rowSpan={2}
                      />
                      {hourIntervals.map((interval) => {
                        const isCurrentHour = new Date().getHours() === parseInt(interval.hour, 10)
                        return (
                          <HeaderCell
                            key={interval.hour}
                            colSpan={4}
                            sx={{
                              position: "sticky",
                              backgroundColor: isCurrentHour ? "mainColor" : "#F5F4FC",
                              top: 0,
                              zIndex: 2,
                              border: "none",
                              ...(isCurrentHour && mainColor),
                            }}
                          >
                            {interval.hour}
                          </HeaderCell>
                        )
                      })}
                    </TableRow>
                    <TableRow>
                      {hourIntervals.map((hour) =>
                        MIN_INTERVALE.map((minute) => (
                          <HeaderCell
                            key={`${hour.hour}:${minute}`}
                            ref={minuteCellRef}
                            sx={{
                              position: "sticky",
                              top: 32,
                              zIndex: 2,
                              fontSize: "0.75rem",
                              paddingInline: (theme) => theme.spacing((4 * zoomLevel) / 100),
                            }}
                          >
                            {minute}
                          </HeaderCell>
                        ))
                      )}
                    </TableRow>
                  </TableHead>
                  <TableBody>
                    {[
                      { id: "", name: "Non Affecté", company: "", vehicleId: "", immatricule: "", phoneNumber: "" },
                      ...filteredDrivers.filter((d) => d.id !== "")
                    ].map((driver) => (
                      <TableRow
                        key={driver.id}
                        hover
                        sx={{
                          ...(driver.id === "" && {
                            position: "sticky",
                            top: 64,
                            zIndex: 4,
                            backgroundColor: "background.paper",
                          }),
                        }}
                      >
                        <TableCell
                          sx={{
                            position: "sticky",
                            left: 0,
                            backgroundColor: "background.paper",
                            zIndex: driver.id === "" ? 3 : 2,
                            maxWidth: 150,
                            minWidth: 150,
                            ...(driver.id === "" && {
                              "&::before": {
                                content: '""',
                                position: "absolute",
                                top: 0,
                                left: -1,
                                width: "100%",
                                height: "100%",
                                backgroundColor: "primary.lighter",
                                zIndex: -2,
                              },
                              "&::after": {
                                content: '""',
                                position: "absolute",
                                top: 0,
                                left: 0,
                                right: 0,
                                bottom: 0,
                                backgroundColor: "background.paper",
                                borderTopLeftRadius: 16,
                                zIndex: -1,
                              },
                            }),
                          }}
                          onMouseEnter={(e) => handlePopoverOpen(e, driver)}
                          onMouseLeave={handlePopoverClose}
                        >
                          <Box sx={{ width: "100%" }} display="flex" flexDirection="column">
                            <Box sx={{ display: "flex", alignItems: "center", overflow: "hidden" }}>
                              <FontAwesome
                                icon={driver.id === "" ? faXmark : faUserTie}
                                color="primary.main"
                                width={12}
                                sx={{ mr: 1, flexShrink: 0 }}
                              />
                              <Typography
                                sx={{
                                  fontWeight: 500,
                                  overflow: "hidden",
                                  textOverflow: "ellipsis",
                                  whiteSpace: "nowrap",
                                  flex: 1
                                }}
                                variant="caption"
                                title={driver.name}
                              >
                                {driver.name}
                              </Typography>
                            </Box>

                            {driver.company && (
                              <Box sx={{ display: "flex", alignItems: "center", overflow: "hidden" }}>
                                <FontAwesome icon={faOrcid} color="primary.main" width={12} sx={{ mr: 1, flexShrink: 0 }} />
                                <Typography
                                  sx={{ fontWeight: 500, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", flex: 1 }}
                                  variant="caption"
                                  title={driver.company}
                                >
                                  {driver.company}
                                </Typography>
                              </Box>
                            )}

                            {driver.vehicleId && (
                              <Box sx={{ display: "flex", alignItems: "center", overflow: "hidden" }}>
                                <FontAwesome icon={faCar} color="primary.main" width={12} sx={{ mr: 1, flexShrink: 0 }} />
                                <Typography
                                  sx={{ fontWeight: 500, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", flex: 1 }}
                                  variant="caption"
                                  title={driver.immatricule}
                                >
                                  {driver.immatricule}
                                </Typography>
                              </Box>
                            )}

                            {driver.phoneNumber && (
                              <Box sx={{ display: "flex", alignItems: "center", overflow: "hidden" }}>
                                <FontAwesome icon={faPhone} color="primary.main" width={12} sx={{ mr: 1, flexShrink: 0 }} />
                                <Typography
                                  sx={{ fontWeight: 500, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", flex: 1 }}
                                  variant="caption"
                                  title={driver.phoneNumber}
                                >
                                  {driver.phoneNumber}
                                </Typography>
                              </Box>
                            )}

                            {driver.id === "" && (
                              <Input
                                type="text"
                                placeholder="Rechercher un chauffeur"
                                value={driverQuery}
                                onChange={(e) => setDriverQuery(e.target.value)}
                                sx={{
                                  width: "100%",
                                  mt: 1,
                                  "& .MuiInputBase-input": {
                                    padding: "4px 8px",
                                    fontSize: "0.875rem",
                                  },
                                }}
                              />
                            )}
                          </Box>
                        </TableCell>

                        {hourIntervals.map((hour) =>
                          MIN_INTERVALE.map((minute) => {
                            const paddedHour = hour.hour.padStart(2, "0")
                            const paddedMinute = minute.padStart(2, "0")

                            const driverSlots = planningSlots.filter((slot) => slot.driverId === driver.id)
                            const driverAbsences = scheduleData.absences?.filter((absence) =>
                              absence.driverId === driver.id && isSlotInCell(absence, paddedHour, paddedMinute)
                            ) || []

                            const overlappingGroups = groupOverlappingSlots(driverSlots)
                            const overlappingGroupsAbsences = groupOverlappingSlots(driverAbsences)

                            const slotsInCell = driverSlots.filter((slot) => isSlotInCell(slot, hour.hour, minute))
                            const slotsInCellNone = nonAffectedSlotsPrincipal.filter((slot) =>
                              isSlotInCell(slot, paddedHour, paddedMinute)
                            )

                            const maxGroupHeight = overlappingGroups.reduce((max, group) => Math.max(max, group.length), 0)
                            const maxAbsenceHeight = overlappingGroupsAbsences.reduce((max, group) => Math.max(max, group.length), 0)
                            const totalMaxHeight = Math.max(maxGroupHeight, maxAbsenceHeight)
                            const cellHeight = totalMaxHeight <= 1 ? "100%" : `${(SLOT_HEIGHT + 2) * totalMaxHeight}px`

                            return (
                              <DroppableCell key={`${hour.hour}:${minute}`} driverId={driver.id} height={cellHeight}>
                                {isAbsenceFilterActive && driverAbsences.map((absence) => {
                                  const indexInGroup = findSlotIndexInGroup(absence, overlappingGroupsAbsences)
                                  return (
                                    <AbsenceBlock
                                      key={absence.id}
                                      absence={absence}
                                      width={calculateTimeSlotWidth(
                                        absence.startHeure,
                                        absence.startMinute,
                                        absence.endHeure,
                                        absence.endMinute,
                                        INTERVAL_MINUTES,
                                        cellWidth
                                      )}
                                      height={totalMaxHeight <= 1 ? "100%" : `${SLOT_HEIGHT}px`}
                                      top={totalMaxHeight <= 1 ? 0 : indexInGroup * (SLOT_HEIGHT + 2)}
                                      colorDegree={colorDegree}
                                    />
                                  )
                                })}

                                {slotsInCell.map((slot) => {
                                  const indexInGroup = findSlotIndexInGroup(slot, overlappingGroups)
                                  return (
                                    <DriverDraggableTimeSlot
                                      key={slot.id}
                                      slot={slot}
                                      cellWidth={cellWidth}
                                      width={calculateTimeSlotWidth(
                                        slot.startHeure,
                                        slot.startMinute,
                                        slot.endHeure,
                                        slot.endMinute,
                                        INTERVAL_MINUTES,
                                        cellWidth
                                      )}
                                      height={totalMaxHeight <= 1 ? "100%" : `${SLOT_HEIGHT}px`}
                                      top={indexInGroup * (SLOT_HEIGHT + 2)}
                                      left={calculateSlotLeftOffset(slot, paddedHour, paddedMinute, cellWidth)}
                                      handlePopoverOpenT={handlePopoverOpenT}
                                      handlePopoverCloseT={handlePopoverCloseT}
                                      onDoubleClick={() => handleTimeSlotDoubleClick(slot)}
                                      onCopySlot={() => openPersonalizedPopUp(slot)}
                                      colorDegree={colorDegree}
                                      onDisaffectSlot={(driverId, slotId) => handleDisaffectSlot(driverId, slotId)}
                                      setOpenRoadmapDialog={setOpenRoadmapDialog}
                                      setPlanningDriver={setPlanningDriver}
                                      driver={
                                        {
                                          id: slot.driverId,
                                          name: driver.name,
                                          departmentId: "",
                                          departmentName: ""
                                        }
                                      }

                                    />
                                  )
                                })}

                                {driver.id === "" && slotsInCellNone.map((slot) => {
                                  const indexInGroup = findSlotIndexInGroup(slot, overlappingGroups)
                                  return (
                                    <DriverDraggableTimeSlot
                                      key={slot.id}
                                      slot={slot}
                                      cellWidth={cellWidth}
                                      width={calculateTimeSlotWidth(
                                        slot.startHeure,
                                        slot.startMinute,
                                        slot.endHeure,
                                        slot.endMinute,
                                        INTERVAL_MINUTES,
                                        cellWidth
                                      )}
                                      height={totalMaxHeight <= 1 ? "100%" : `${SLOT_HEIGHT}px`}
                                      top={indexInGroup * (SLOT_HEIGHT + 2)}
                                      left={calculateSlotLeftOffset(slot, paddedHour, paddedMinute, cellWidth)}
                                      handlePopoverOpenT={handlePopoverOpenT}
                                      handlePopoverCloseT={handlePopoverCloseT}
                                      onDoubleClick={() => handleTimeSlotDoubleClick(slot)}
                                      onCopySlot={() => openPersonalizedPopUp(slot)}
                                      colorDegree={colorDegree}
                                      onDisaffectSlot={(driverId, slotId) => handleDisaffectSlot(driverId, slotId)}
                                      setOpenRoadmapDialog={setOpenRoadmapDialog}
                                      setPlanningDriver={setPlanningDriver}
                                      driver={
                                        {
                                          id: slot.driverId,
                                          name: driver.name,
                                          departmentId: "",
                                          departmentName: ""
                                        }
                                      }

                                    />
                                  )
                                })}
                              </DroppableCell>
                            )
                          })
                        )}
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </StyledTableContainer>
            </Box>
          )}

          <DriverDetailsPopover anchorEl={anchorEl} driver={hoveredDriver} onClose={handlePopoverClose} />

          {hoveredSlot && (
            <ConditionalComponent
              isValid={"vehicle" in hoveredSlot}
              defaultComponent={
                <TrajetDetailsPopover
                  anchorEl={anchorElT}
                  color={("driverId" in hoveredSlot && (hoveredSlot as DriverTimeSlot).driverId === null) ? StatusColor.PRIMARY : (hoveredSlot as any).color}
                  onClose={handlePopoverCloseT}
                  data={{
                    circuit: (hoveredSlot as DriverTimeSlot).nameCircuit || (hoveredSlot as DriverTimeSlot).codeCircuit || "Non inclus",
                    trajet: (hoveredSlot as DriverTimeSlot).name || "Non inclus",
                    schedule: `${(hoveredSlot as DriverTimeSlot).date} (${(hoveredSlot as DriverTimeSlot).pickupStartHeure}:${(hoveredSlot as DriverTimeSlot).pickupStartMinute} à ${(hoveredSlot as DriverTimeSlot).returnEndHeure}:${(hoveredSlot as DriverTimeSlot).returnEndMinute})`,
                    wheelchairCount: (hoveredSlot as DriverTimeSlot).nbPassengers || 5,
                  }}
                />
              }
            >
              <InterventionDetailsPopover anchorEl={anchorElT} onClose={handlePopoverCloseT} slot={hoveredSlot} />
            </ConditionalComponent>
          )}

          <Box
            sx={{
              position: "fixed",
              bottom: 0,
              right: 0,
              width: isBottomDrawerOpen ? `${DRAWER_WIDTH}px` : "0px",
              height: "100vh",
              transition: "width 0.3s ease-in-out",
              zIndex: 1200,
              overflow: "hidden",
            }}
          >
            {isBottomDrawerOpen && renderSidebarContent()}
          </Box>

          {/* <DragOverlay>
            {activeTimeSlot && (
              <TimeSlotBlock>
                {`${activeTimeSlot.startHeure}:${activeTimeSlot.startMinute} - ${activeTimeSlot.endHeure}:${activeTimeSlot.endMinute}`}
              </TimeSlotBlock>
            )}
          </DragOverlay> */}
        </Box>

        <CustomDrawer
          drawerWidth={DRAWER_WIDTH}
          open={isDrawerOpen}
          onClose={() => {
            setIsDrawerOpen(false)
            setDrawerMode("view")
          }}
        >
          <ConditionalComponent isValid={isDrawerOpen && tripData !== null}>
            <TrajetPlanningForm
              isDrawerElement
              trajet={tripData!}
              mode={drawerMode}
              setDrawerMode={setDrawerMode}
              onClose={() => setIsDrawerOpen(false)}
              onSave={() => { }}
              tableHead={tableHead}
              handleView={() => { }}
              drivers={driversList}
              currentTimeSlot={currentTimeSlot}
            />
          </ConditionalComponent>

        </CustomDrawer>

        <CustomDrawer
          drawerWidth={DRAWER_WIDTH}
          open={isDrawerOpenPersonalized}
          onClose={() => {
            setIsDrawerOpenPersonalized(false)
            setDrawerMode("view")
          }}
        >
          <ConditionalComponent isValid={isDrawerOpenPersonalized && tripData !== null}>
            {tripData && (
              <TrajetPlanningForm
                isDrawerElement
                trajet={tripData}
                mode="copy"
                setDrawerMode={setDrawerMode}
                onClose={() => setIsDrawerOpenPersonalized(false)}
                onSave={() => { }}
                tableHead={tableHead}
                handleView={() => { }}
                drivers={driversList}
                currentTimeSlot={currentTimeSlot}
                defaultSelectedType="personnalisé"
              />
            )}
          </ConditionalComponent>

        </CustomDrawer>
      </DndContext>

      <ConfirmDialog
        open={confirmDialog.open}
        title="Confirmer le déplacement du créneau"
        content={`Voulez-vous vraiment déplacer le trajet du ${confirmDialog.slot?.date} ${confirmDialog.slot?.startHeure}h${confirmDialog.slot?.startMinute} à ${confirmDialog.slot?.endHeure}h${confirmDialog.slot?.endMinute} vers un autre chauffeur ?`}
        onConfirm={() => setConfirmDialog({ open: false, slot: null })}
        onCancel={() => setConfirmDialog({ open: false, slot: null })}
        confirmButtonText="Déplacer"
        confirmButtonColor="primary"
      />

      <ConfirmDialog
        open={affectationDialog.open}
        title={
          affectationDialog.action === 'affect'
            ? "Confirmer l'affectation du créneau"
            : affectationDialog.action === 'reaffect'
              ? "Confirmer la réaffectation du créneau"
              : "Confirmer la désaffectation du créneau"
        }
        content={
          affectationDialog.action === 'affect'
            ? `Voulez-vous affecter le trajet du ${affectationDialog.slot?.date} (${affectationDialog.slot?.startHeure}:${affectationDialog.slot?.startMinute} à ${affectationDialog.slot?.endHeure}:${affectationDialog.slot?.endMinute}) au chauffeur "${affectationDialog.targetDriverName}" ?`
            : affectationDialog.action === 'reaffect'
              ? `Voulez-vous réaffecter le trajet du ${affectationDialog.slot?.date} (${affectationDialog.slot?.startHeure}:${affectationDialog.slot?.startMinute} à ${affectationDialog.slot?.endHeure}:${affectationDialog.slot?.endMinute}) au chauffeur "${affectationDialog.targetDriverName}" ?`
              : `Voulez-vous désaffecter le trajet du ${affectationDialog.slot?.date} (${affectationDialog.slot?.startHeure}:${affectationDialog.slot?.startMinute} à ${affectationDialog.slot?.endHeure}:${affectationDialog.slot?.endMinute}) ?`
        }
        onConfirm={handleConfirmAffectation}
        onCancel={handleCancelAffectation}
        confirmButtonText={
          affectationDialog.action === 'affect'
            ? "Affecter"
            : affectationDialog.action === 'reaffect'
              ? "Réaffecter"
              : "Désaffecter"
        }
        confirmButtonColor={
          affectationDialog.action === 'disaffect' ? "error" : "success"
        }
      />
      <SendDriverPlanningDialog
        open={openRoadmapDialog}
        onClose={() => setOpenRoadmapDialog(false)}
        onSend={() => { }}
        planningDriver={planningDriver}
      />

    </Box>
  )
}

const HeaderCell = styled(TableCell)(({ theme }) => ({
  fontWeight: 500,
  padding: theme.spacing(0.5),
  textAlign: "center",
  borderBlock: `1px solid ${theme.palette.divider}`,
  borderLeft: `1px solid ${theme.palette.divider}`,
  height: 32,
}))

type IntensitySliderProps = {
  colorDegrees: number
  setColorDegree: (value: number) => void
}

function IntensitySlider({ colorDegrees, setColorDegree }: IntensitySliderProps) {
  return (
    <Box sx={{ display: "flex", flexDirection: "column", maxWidth: 340, minWidth: 200, alignSelf: "flex-start" }}>
      <Box sx={{ display: "flex", alignItems: "center", ml: 0.5 }}>
        <Typography fontWeight={600} fontSize={16} sx={{ color: "primary.main" }}>
          Intensité des couleurs
        </Typography>
        <Box flex={1} />
        <Typography fontSize={15} sx={{ color: "primary.main", fontWeight: 500 }}>
          {colorDegrees}%
        </Typography>
      </Box>
      <CustomSlider
        value={colorDegrees}
        min={20}
        max={99}
        step={1}
        onChange={(_, v) => { setColorDegree(v as number) }}
        aria-labelledby="continuous-slider"
        sx={{
          color: "primary.main",
          "& .MuiSlider-thumb": {
            height: 15,
            width: 15,
            backgroundColor: "#fff",
            border: "5px solid",
            borderColor: "primary.main",
            boxShadow: "0 2px 6px rgba(0,0,0,0.10)",
          },
          "& .MuiSlider-rail": { backgroundColor: "#ECECEC", opacity: 1 },
          "& .MuiSlider-track": { backgroundColor: "primary.main", border: "none" },
        }}
      />

    </Box>
  )
}
