"use client"

import React, { useMemo } 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 { faCar, faGripVertical, faCopy } from "@fortawesome/free-solid-svg-icons"
import { lightColor } from "@/shared/components/table/styles"
import type { DraggableTimeSlotProps } from "../types"
import { format, parseISO } from "date-fns"
import { fr } from "date-fns/locale"
import CustomTooltip from "@/shared/components/tooltips/tooltip-custom"


export const TimeSlotBlock = styled(Box)(({ theme }) => ({
  position: "relative",
  display: "flex",
  flexDirection: "column",
  justifyContent: "center",
  alignItems: "center",
  borderRadius: 4,
  padding: theme.spacing(0.5),
  fontSize: 12,
  cursor: "pointer",
  zIndex: 1,
  overflow: "hidden",
  whiteSpace: "nowrap",
  textOverflow: "ellipsis",
  boxSizing: "border-box",
  border: "1px solid",
  transition: "all 0.2s ease-in-out",
  height: "100%",
  width: "100%",
  "&:hover": {
    opacity: 0.9,
  },
}))

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

  const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null)
  const open = Boolean(anchorEl)

  const handleClick = (event: React.MouseEvent<HTMLElement>) => {
    setAnchorEl(event.currentTarget)
  }

  const handleClose = () => {
    setAnchorEl(null)
  }

  const dateRange = useMemo(() => {
    try {
      const startDate = format(parseISO(slot.startDate), 'dd MMM', { locale: fr })
      const endDate = format(parseISO(slot.endDate), 'dd MMM', { locale: fr })
      return `${startDate} - ${endDate}`
    } catch (error) {
      console.error("Error formatting date range:", error)
      return "Date invalide"
    }
  }, [slot.startDate, slot.endDate])

  const timeRange = useMemo(() => {
    if (slot.startHeure && slot.endHeure) {
      return `${slot.startHeure}:${slot.startMinute || '00'} - ${slot.endHeure}:${slot.endMinute || '00'}`;
    }
    return "Journée complète";
  }, [slot.startHeure, slot.startMinute, slot.endHeure, slot.endMinute]);

  const style = {
    backgroundColor: slot.color,
    borderColor: slot.color,
    color: "#fff",
    transform: transform ? `translate3d(${transform.x}px, ${transform.y}px, 0)` : undefined,
  }

  return (
    <>
      <TimeSlotBlock
        ref={setNodeRef}
        {...listeners}
        {...attributes}
        style={style}
        onMouseEnter={(e) => handlePopoverOpenT(e, slot)}
        onMouseLeave={handlePopoverCloseT}
        onDoubleClick={onDoubleClick}
      >
        <Box sx={{ display: "flex", alignItems: "center", justifyContent: "space-between", width: "100%" }}>
          <FontAwesome icon={faCar} width={12} />
          <Box sx={{ 
            display: "flex", 
            flexDirection: "column", 
            textAlign: "center", 
            fontWeight: 500, 
            mx: 1, 
            flexGrow: 1 
          }}>
            <Box>{dateRange}</Box>
            <Box sx={{ fontSize: '0.7rem', opacity: 0.9 }}>{timeRange}</Box>
          </Box>
          <IconButton
            size="small"
            sx={{ color: "#fff", p: 0 }}
            onClick={handleClick}
          >
            <FontAwesome icon={faGripVertical} width={12} />
          </IconButton>
        </Box>
      </TimeSlotBlock>

      <Menu
        anchorEl={anchorEl}
        open={open}
        onClose={handleClose}
      >
        <MenuItem onClick={handleClose}>
          <CustomTooltip title="Copier Location" arrow>
            <IconButton size="small" sx={lightColor}>
              <FontAwesome icon={faCopy} width={12} />
            </IconButton>
          </CustomTooltip>
        </MenuItem>
      </Menu>
    </>
  )
}