import { Table, TableBody, TableHead, TableRow, TableCell, Typography, Box } from '@mui/material';
import { useDroppable } from '@dnd-kit/core';
import { alpha } from '@mui/material/styles';
import FontAwesome from '@/shared/components/fontawesome';
import { faCar, faUser } from '@fortawesome/free-solid-svg-icons';
import { faOrcid } from '@fortawesome/free-brands-svg-icons';
import { HeaderCell } from '../styles/planning.styles';
import { StyledTableContainer } from '@/shared/theme/css';
import {
  calculateTimeSlotWidth,
  groupOverlappingSlots,
  findSlotIndexInGroup,
  isTimeSlotInCell,
  getHourIntervals,
  getMinuteIntervals,
  convertEventsToTimeSlots,
  extractUniqueVehicles,
} from '../utils/planning-utils';
import { SLOT_HEIGHT } from '../constants/planning-constants';
import { VehicleRow } from './vehicle-row';
import { DroppableCellProps, Vehicle, ScheduleData, TimeSlot } from '../types/planning-types';
interface PlanningTableProps {
  scheduleData: ScheduleData;
  selectedDate: Date;
  cellWidth: number;
  headerCellRef: React.RefObject<HTMLTableCellElement>;
  minuteCellRef: React.RefObject<HTMLTableCellElement>;
  leftColumnWidth: number;
  onTimeSlotDoubleClick: (slot: TimeSlot) => void;
  onPopoverOpen: (event: React.MouseEvent<HTMLElement>, vehicle: Vehicle) => void;
  onPopoverOpenT: (event: React.MouseEvent<HTMLElement>, slot: TimeSlot) => void;
  onPopoverClose: () => void;
  onPopoverCloseT: () => void;
}
const DroppableCell = ({ vehicleId, children, height }:DroppableCellProps) => {
  const { setNodeRef, isOver } = useDroppable({ id: vehicleId });
  return (
    <TableCell
      ref={setNodeRef}
      sx={{
        position: 'relative',
        padding: 0,
        borderBottom: (theme) => `1px solid ${theme.palette.divider}`,
        borderLeft: (theme) => `1px solid ${theme.palette.divider}`,
        backgroundColor: (theme) => (isOver ? alpha(theme.palette.primary.main, 0.1) : 'white'),
        '&:last-of-type': { borderRight: (theme) => `1px solid ${theme.palette.divider}` },
        height,
        outline: 'none',
      }}
    >
      {children}
    </TableCell>
  );
};

export const PlanningTable = ({
  scheduleData,
  selectedDate,
  cellWidth,
  headerCellRef,
  minuteCellRef,
  leftColumnWidth,
  onTimeSlotDoubleClick,
  onPopoverOpen,
  onPopoverOpenT,
  onPopoverClose,
  onPopoverCloseT,
}: PlanningTableProps) => (
  <StyledTableContainer sx={{ flex: 1, 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}
          />
          {/* Hour headers */}
          {getHourIntervals(selectedDate).map((interval) => (
            <HeaderCell
              key={interval.hour}
              colSpan={4}
              sx={{
                position: 'sticky',
                backgroundColor: interval.hour === new Date().getHours().toString().padStart(2, '0') ? 'primary.main' : '#F5F4FC',
                top: 0,
                zIndex: 2,
                border: 'none',
                color: interval.hour === new Date().getHours().toString().padStart(2, '0') ? 'white' : 'inherit',
              }}
            >
              {interval.hour}
            </HeaderCell>
          ))}
        </TableRow>
        {/* Minute headers */}
        <TableRow>
          {getHourIntervals(selectedDate).map((hour) =>
            getMinuteIntervals().map((minute) => (
              <HeaderCell
                key={`${hour.hour}:${minute}`}
                ref={minuteCellRef}
                sx={{
                  position: 'sticky',
                  top: 32,
                  zIndex: 2,
                  fontSize: '0.75rem',
                  paddingInline: (theme) => theme.spacing((4 * 50) / 100),
                }}
              >
                {minute}
              </HeaderCell>
            ))
          )}
        </TableRow>
      </TableHead>
      <TableBody>
        {/* Vehicle rows */}
        {scheduleData.vehicles.map((vehicle) => (
          <VehicleRow
            key={vehicle.id}
            vehicle={vehicle}
            scheduleData={scheduleData}
            selectedDate={selectedDate}
            cellWidth={cellWidth}
            onTimeSlotDoubleClick={onTimeSlotDoubleClick}
            onPopoverOpen={onPopoverOpen}
            onPopoverOpenT={onPopoverOpenT}
            onPopoverClose={onPopoverClose}
            onPopoverCloseT={onPopoverCloseT}
          />
        ))}
      </TableBody>
    </Table>
  </StyledTableContainer>
); 