import { TableCell } from '@mui/material';
import { DroppableCell } from './styled-components';
import { calculateTimeSlotWidth } from '../utils/schedule-utils';
import { isTimeSlotInCell } from '../utils/planning-utils';
import { groupOverlappingSlots, findSlotIndexInGroup } from '../utils/schedule-utils';
import { SLOT_HEIGHT } from '../constants/planning-constants';
import { VehicleTimeSlotBlock } from './draggable-time-slot';

interface TimeSlotCellProps {
  vehicle: any;
  hour: { hour: string };
  minute: string;
  scheduleData: any;
  cellWidth: number;
  onTimeSlotDoubleClick: (slot: any) => void;
  onPopoverOpenT: (event: React.MouseEvent<HTMLElement>, slot: any) => void;
  onPopoverCloseT: () => void;
}

export const TimeSlotCell = ({
  vehicle,
  hour,
  minute,
  scheduleData,
  cellWidth,
  onTimeSlotDoubleClick,
  onPopoverOpenT,
  onPopoverCloseT,
}: TimeSlotCellProps) => {
  const vehicleSlots = scheduleData.timeSlots.filter(
    (slot: any) => slot.vehicleId === vehicle.id
  );
  
  const overlappingGroups = groupOverlappingSlots(vehicleSlots);
  
  const slotsInCell = vehicleSlots.filter((slot: any) =>
    isTimeSlotInCell(slot, hour.hour, minute)
  );

  const maxGroupHeight = overlappingGroups.reduce(
    (max: number, group: any[]) => Math.max(max, group.length),
    0
  );

  const cellHeight = maxGroupHeight <= 1 ? '100%' : `${(SLOT_HEIGHT + 2) * maxGroupHeight}px`;

  return (
    <DroppableCell
      isOver={false}
      height={cellHeight}
    >
      {slotsInCell.map((slot: any) => {
        const indexInGroup = findSlotIndexInGroup(slot, overlappingGroups);
        return (
          <VehicleTimeSlotBlock
            key={slot.id}
            slot={slot}
            width={calculateTimeSlotWidth(
              slot.startHeure,
              slot.startMinute,
              slot.endHeure,
              slot.endMinute,
              15, // INTERVAL_MINUTES
              cellWidth
            )}
            height={maxGroupHeight <= 1 ? '100%' : `${SLOT_HEIGHT}px`}
            top={maxGroupHeight <= 1 ? 0 : indexInGroup * (SLOT_HEIGHT + 2)}
            onDoubleClick={() => onTimeSlotDoubleClick(slot)}
            handlePopoverOpenT={onPopoverOpenT}
            handlePopoverCloseT={onPopoverCloseT}
          />
        );
      })}
    </DroppableCell>
  );
}; 