"use client"

import type React from "react"
import { useDraggable } from "@dnd-kit/core"
import { styled } from "@mui/material/styles"
import { Box, IconButton, Menu, MenuItem } from "@mui/material"
import FontAwesome from "@/shared/components/fontawesome"
import { faWheelchair, faGripVertical, faCopy, faGear } from "@fortawesome/free-solid-svg-icons"
import SvgColor from "@/shared/components/svg-color"
import { lightColor, greyColor } from "@/shared/components/table/styles"
import type { DraggableTimeSlotProps } from "../types"
import { getBgColor } from "../utils/schedule-utils"
import { useMemo, useState } from "react"
import CustomTooltip from "@/shared/components/tooltips/tooltip-custom"
import { AffectedIndicator, DragHandle, TimeSlotBlock } from "../style"
import { TypeTrajet } from "@/shared/types/trajet"
import ConditionalComponent from "@/shared/components/table/ConditionalComponent"

export function DriverDraggableTimeSlot({
  slot,
  width,
  top,
  height,
  handlePopoverOpenT,
  handlePopoverCloseT,
  onDoubleClick,
  onCopySlot,
}: DraggableTimeSlotProps) {
  const { attributes, listeners, setNodeRef, transform, isDragging } = useDraggable({
    id: slot.id,
    data: slot,
  })

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

  const style = transform
    ? {
        transform: `translate3d(${transform.x}px, ${transform.y}px, 0)`,
      }
    : undefined
  const isAffected = slot.driverId !== "1"

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

  const handleContextMenu = (event: React.MouseEvent) => {
    event.preventDefault()
    setContextMenu(
      contextMenu === null
        ? {
          mouseX: event.clientX,
          mouseY: event.clientY,
        }
        : null,
    )
  }

  const handleCloseContextMenu = () => {
    setContextMenu(null)
  }

  const handleMenuAction = (action: string) => {
    if(action === 'copy' && onCopySlot) {
      onCopySlot(slot);
    }
    handleCloseContextMenu();
  }

  const bgColor = getBgColor(slot.color)
  const fontSize = useMemo(() => {
    if (width < 150) return 9
    if (width < 200) return 10
    return 11
  }, [width])

  return (
    <>
      <TimeSlotBlock
        ref={setNodeRef}
        onMouseEnter={(e) => handlePopoverOpenT(e, slot)}
        onMouseLeave={handlePopoverCloseT}
        onDoubleClick={handleDoubleClick}
        onContextMenu={handleContextMenu}
        isDragging={isDragging}
        style={{ ...style, top: `${top}px`, height }}
        sx={{
          width,
          border: "none",
          pl: 1,
          pr: 2,
          color: isAffected ? slot.color : lightColor.color,
          backgroundColor: isAffected ? bgColor : lightColor.bgcolor,
        }}
      >
        {isAffected && !isDragging ? (
          <>
            <AffectedIndicator
              sx={{
                right: "100%",
                width: "40%",
                ...greyColor,
                fontSize: `${fontSize}px`,
              }}
            >
              <SvgColor src="/assets/icons/form/ic_house.svg" sx={{ width: 12, height: 12 }} />
              <Box>{`-:- - ${slot.startHeure}:${slot.startMinute}`}</Box>
            </AffectedIndicator>

            <AffectedIndicator
              sx={{
                left: "100%",
                width: "30%",
                ...greyColor,
                fontSize: `${fontSize}px`,
              }}
            >
              <SvgColor src="/assets/icons/form/ic_house.svg" sx={{ width: 12, height: 12 }} />
              <Box>{`${slot.endHeure}:${slot.endMinute} - -:-`}</Box>
            </AffectedIndicator>
          </>
        ) : <></>}

        <Box sx={{ display: "flex", gap: "3%", flexDirection: "column", fontSize: `${fontSize}px` }}>
          <Box sx={{ display: "flex", gap: 0.5, alignItems: "center" }}>
            <ConditionalComponent isValid={width > 100}>
              <FontAwesome icon={faWheelchair} width={12} />
              <ConditionalComponent isValid={slot.trajet?.typeTrajet === TypeTrajet.personnalise}>
                <CustomTooltip title={`Trajet personnalisé`} arrow>
                  <FontAwesome icon={faGear} width={12} />
                </CustomTooltip>
              </ConditionalComponent>
            </ConditionalComponent>
          </Box>
          {`${slot.startHeure}:${slot.startMinute} - ${slot.endHeure}:${slot.endMinute}`}
        </Box>
        <DragHandle {...listeners} {...attributes}>
          <FontAwesome icon={faGripVertical} width={12} />
        </DragHandle>
      </TimeSlotBlock>

      <Menu
        open={contextMenu !== null}
        onClose={handleCloseContextMenu}
        anchorReference="anchorPosition"
        anchorPosition={
          contextMenu !== null
            ? { top: contextMenu.mouseY, left: contextMenu.mouseX }
            : undefined
        }
      >
        <MenuItem  onClick={() => handleMenuAction('copy')}>
          <CustomTooltip title={`Copier Trajet`} arrow>
            <IconButton onClick={()=> void 0} size="small" sx={lightColor}>
              <FontAwesome icon={faCopy} width={14} />
            </IconButton>
          </CustomTooltip>
        </MenuItem>
      </Menu>
    </>
  )
}
