"use client"

import type React from "react"
import { memo, useState, useCallback } from "react"
import { useDraggable } from "@dnd-kit/core"
import { Box, IconButton, Menu, MenuItem, Typography } from "@mui/material"
import FontAwesome from "@/shared/components/fontawesome"
import { faGripVertical, faCopy, faRemove, faEnvelope } from "@fortawesome/free-solid-svg-icons"
import SvgColor from "@/shared/components/svg-color"
import { greyColor } from "@/shared/components/table/styles"
import type { DraggableTimeSlotProps } from "../types"
import { calculateTimeSlotWidth } from "../utils/schedule-utils"
import CustomTooltip from "@/shared/components/tooltips/tooltip-custom"
import { DragHandle, TimeSlotBlock } from "../style"
import { INTERVAL_MINUTES } from "../utils/schedule-utils"
import { getBgColor } from "@/shared/sections/planning/utils/schedule-utils"
import dayjs from "dayjs"
import { useDriverStore } from "@/shared/api/stores/driverStore"

const getFontSize = (currentWidth: number): number => {
  if (currentWidth < 150) return 9
  if (currentWidth < 200) return 10
  return 11
}

export const DriverDraggableTimeSlot = memo(function DriverDraggableTimeSlot({
  slot,
  width,
  top,
  height,
  left = 0,
  handlePopoverOpenT,
  handlePopoverCloseT,
  onDoubleClick,
  onCopySlot,
  onDisaffectSlot,
  cellWidth,
  colorDegree = 90,
  setOpenRoadmapDialog,
  setPlanningDriver,
  driver
}: DraggableTimeSlotProps) {
  const { attributes, listeners, setNodeRef, transform, isDragging } = useDraggable({
    id: slot.isAssigned ? slot.id : `non-affected-${slot.id}`,
    data: slot.isAssigned ? slot : { ...slot, isFromSidebar: true },
  })
  const getDriverDepatmentName = useDriverStore((state) => state.getDriverDepatmentName);

  const handleSelectDriver = async () => {
   const departmentName = await getDriverDepatmentName(slot.driverId);
    setPlanningDriver({
      id: Number(slot.driverId),
      name: driver.name,
      departmentId: 3,
      departmentName: departmentName || "Non défini",
      planningDay: dayjs(slot.date), 
    });
  };

  const pickupStartDiffers = slot.pickupStartHeure !== slot.startHeure || slot.pickupStartMinute !== slot.startMinute
  const returnEndDiffers = slot.returnEndHeure !== slot.endHeure || slot.returnEndMinute !== slot.endMinute
  const pickupWidth = pickupStartDiffers
    ? calculateTimeSlotWidth(
      slot.pickupStartHeure,
      slot.pickupStartMinute,
      slot.startHeure,
      slot.startMinute,
      INTERVAL_MINUTES,
      cellWidth
    )
    : 0
    
  const returnWidth = returnEndDiffers
    ? calculateTimeSlotWidth(
      slot.endHeure,
      slot.endMinute,
      slot.returnEndHeure,
      slot.returnEndMinute,
      INTERVAL_MINUTES,
      cellWidth
    )
    : 0

  const MIN_WIDTH = 30
  const adjustedWidth = Math.max(width, MIN_WIDTH)

  const [contextMenu, setContextMenu] = useState<{
    mouseX: number
    mouseY: number
  } | null>(null)

  const isAffected = slot.driverId !== null &&
    slot.driverId !== undefined &&
    slot.driverId !== "" &&
    String(slot.driverId).trim() !== ""

  const handleDoubleClick = useCallback((e: React.MouseEvent<HTMLElement>) => {
    if (!isDragging) {
      onDoubleClick(slot)
    }
  }, [isDragging, onDoubleClick, slot])

  const handleContextMenu = useCallback((event: React.MouseEvent) => {
    event.preventDefault()
    setContextMenu({
      mouseX: event.clientX,
      mouseY: event.clientY,
    })
  }, [])

  const handleCloseContextMenu = useCallback(() => {
    setContextMenu(null)
  }, [])

  const handleCopyAction = useCallback(() => {
    if (onCopySlot) {
      onCopySlot(slot)
    }
    handleCloseContextMenu()
  }, [onCopySlot, slot, handleCloseContextMenu])

  const handleDisaffectAction = useCallback(() => {
    onDisaffectSlot(slot.driverId, slot.id)
    handleCloseContextMenu()
  }, [onDisaffectSlot, slot.driverId, slot.id, handleCloseContextMenu])

  const bgColor = getBgColor(slot.color, colorDegree)
  const totalWidth = pickupWidth + adjustedWidth + returnWidth

  const draggableContainerStyle: React.CSSProperties = {
    top: `${top}px`,
    left: `${left}px`,
    height,
    width: totalWidth,
    position: "absolute",
    willChange: isDragging ? 'transform' : 'auto',
    ...(transform ? { 
      transform: `translate3d(${transform.x}px, ${transform.y}px, 0)`,
      transition: 'none'
    } : {}),
  }

  return (
    <>
      <div
        ref={setNodeRef}
        onMouseEnter={(e) => !isDragging && handlePopoverOpenT(e, slot)}
        onMouseLeave={handlePopoverCloseT}
        onDoubleClick={handleDoubleClick}
        onContextMenu={handleContextMenu}
        style={draggableContainerStyle}
        className="relative"
        data-slot-id={slot.id}
      >
        {pickupStartDiffers && isAffected && !isDragging && (
          <TimeSlotBlock
            isDragging={false}
            sx={{
              width: pickupWidth,
              border: "none",
              pl: 1,
              pr: 2,
              ...greyColor,
              position: "absolute",
              left: 0,
              top: 0,
              height: "100%",
            }}
          >
            <SvgColor src="/assets/icons/form/ic_house.svg" sx={{ width: 12, height: 12 }} />
            <Box sx={{ fontSize: `${getFontSize(pickupWidth)}px` }}>
              {`${slot.pickupStartHeure}:${slot.pickupStartMinute} - ${slot.startHeure}:${slot.startMinute}`}
            </Box>
          </TimeSlotBlock>
        )}

        <TimeSlotBlock
          isDragging={isDragging}
          sx={{
            width: adjustedWidth,
            pl: 1,
            pr: 2,
            color : (colorDegree < 50 ? "#fff" : slot.color),
            backgroundColor:  bgColor , 
            border: !isAffected ? `1px dashed ${slot.color}` : "none",
            position: "absolute",
            left: pickupWidth,
            top: 0,
            height: "100%",
            opacity: isAffected ? 1 : 0.8,
          }}
        >
          <Box sx={{ display: "flex", gap: "3%", flexDirection: "column", fontSize: `${getFontSize(adjustedWidth)}px` }}>
            {`${slot.startHeure}:${slot.startMinute} - ${slot.endHeure}:${slot.endMinute}`}
          </Box>
          <DragHandle {...listeners} {...attributes}>
            <FontAwesome icon={faGripVertical} width={12} />
          </DragHandle>
        </TimeSlotBlock>

        {returnEndDiffers && isAffected && !isDragging && (
          <TimeSlotBlock
            isDragging={false}
            sx={{
              width: returnWidth,
              border: "none",
              pl: 1,
              pr: 2,
              ...greyColor,
              position: "absolute",
              left: pickupWidth + adjustedWidth,
              top: 0,
              height: "100%",
            }}
          >
            <SvgColor src="/assets/icons/form/ic_house.svg" sx={{ width: 12, height: 12 }} />
            <Box sx={{ fontSize: `${getFontSize(returnWidth)}px` }}>
              {`${slot.endHeure}:${slot.endMinute} - ${slot.returnEndHeure}:${slot.returnEndMinute}`}
            </Box>
          </TimeSlotBlock>
        )}
      </div>
      
      <Menu
        open={contextMenu !== null}
        onClose={handleCloseContextMenu}
        anchorReference="anchorPosition"
        anchorPosition={contextMenu !== null ? { top: contextMenu.mouseY, left: contextMenu.mouseX } : undefined}
      >
        <MenuItem onClick={handleCopyAction}>
          <Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
            <FontAwesome icon={faCopy} width={14} sx={{ color: 'primary.main' }}/>
            <Typography sx={{ color: 'primary.main' }}>
              Personnalisé
            </Typography>
          </Box>
        </MenuItem>
        {isAffected && (
          <>
          <MenuItem onClick={handleDisaffectAction}>
            <Box sx={{ display: "flex", alignItems: "center", overflow: "hidden", gap: 1 }}>
              <FontAwesome icon={faRemove} width={14} sx={{ color: 'primary.main' }}/>
              <Typography sx={{ color: 'primary.main' }}>
                désaffecter
              </Typography>
            </Box>
          </MenuItem>
           <MenuItem   onClick={() =>   {handleSelectDriver(); setOpenRoadmapDialog(true) }}>
              <Box sx={{ display: "flex", alignItems: "center", overflow: "hidden", gap: 1 }}>
                <FontAwesome icon={faEnvelope} width={14} sx={{ color: 'primary.main' }} />
                <Typography sx={{ color: 'primary.main' }}>
                  Feuille de routes
                </Typography>
              </Box>
            </MenuItem></>
        )}
      </Menu>
    </>
  )
}, (prevProps, nextProps) => {
  return (
    prevProps.slot.id === nextProps.slot.id &&
    prevProps.width === nextProps.width &&
    prevProps.top === nextProps.top &&
    prevProps.left === nextProps.left &&
    prevProps.height === nextProps.height &&
    prevProps.cellWidth === nextProps.cellWidth &&
    prevProps.colorDegree === nextProps.colorDegree &&
    prevProps.slot.driverId === nextProps.slot.driverId &&
    prevProps.slot.startHeure === nextProps.slot.startHeure &&
    prevProps.slot.startMinute === nextProps.slot.startMinute
    
  )
})