import { type FC } from 'react';

import Stack from '@material-hu/mui/Stack';

import HuTableCell from '@material-hu/components/design-system/Table/components/TableCell';
import HuTableRow from '@material-hu/components/design-system/Table/components/TableRow';

import { type DaySummary, Incidence } from 'src/types/timeTracking';
import {
  displayHoursAndMinutes,
  type TimeSlotWithEntries,
} from 'src/utils/timeTracking';

import IncidenceSummary from '../../../../components/Incidences/IncidenceSummary';
import { STICKY_OPTIONS_CELL_SX } from '../constants';
import EntriesTime from '../EntriesTime';

import TimeSlotInfo from './TimeSlotInfo';

type Props = {
  timeSlotGroups: TimeSlotWithEntries[];
  isExpanded: boolean;
  dayInfo: DaySummary;
  showIncidencesOnExpandedRow: boolean;
  isDeactivated?: boolean;
};

const GroupSlots: FC<Props> = props => {
  const {
    timeSlotGroups,
    isExpanded,
    dayInfo,
    showIncidencesOnExpandedRow,
    isDeactivated = false,
  } = props;

  const checkIncidencesOnSlot = (
    timeSlotGroup: TimeSlotWithEntries,
    index: number,
  ) => {
    const incidenceTags: Incidence[] = [];
    dayInfo.incidences.forEach(incidence => {
      if (
        incidence === Incidence.LOCATION_INCIDENCE &&
        timeSlotGroup.entries.some(entry => entry.hasLocationIncidence)
      ) {
        incidenceTags.push(incidence);
      }
      // For now LATE incidences apply only to the first time slot
      if (incidence === Incidence.LATE && index === 0) {
        incidenceTags.push(incidence);
      }
    });
    return incidenceTags;
  };

  const tableRowSx = {
    borderBottom: isExpanded ? 'initial' : 'none',
    '&& > td': {
      border: isExpanded ? undefined : 'none',
      opacity: isExpanded ? 1 : 0,
      py: isExpanded ? 2 : 0,
      height: isExpanded ? 'auto' : 0,
      overflow: 'hidden',
      transition: 'padding 250ms ease, opacity 250ms ease',
    },
    '& > td > div': {
      maxHeight: isExpanded ? '200px' : 0,
      overflow: 'hidden',
      transition: 'max-height 250ms ease',
    },
  };

  const isWorkdayWithFlexibleHours =
    dayInfo.isWorkday &&
    dayInfo.holidays.length === 0 &&
    dayInfo.timeOffRequests.length === 0;

  const slotGroups =
    isWorkdayWithFlexibleHours && timeSlotGroups.length === 0
      ? [
          {
            startTime: null,
            endTime: null,
            timeSpan: null,
            entries: [],
            workedHours: 0,
          },
        ]
      : timeSlotGroups;

  // Placeholder row for no scheduled timeslots / marked entries
  if (timeSlotGroups.length === 0 && !isWorkdayWithFlexibleHours) {
    return (
      <HuTableRow sx={tableRowSx}>
        <HuTableCell colSpan={3}></HuTableCell>
        <HuTableCell>
          <div>{displayHoursAndMinutes(0, false, true)}</div>
        </HuTableCell>
        <HuTableCell colSpan={2} />
        <HuTableCell sx={STICKY_OPTIONS_CELL_SX} />
      </HuTableRow>
    );
  }

  return (
    <>
      {slotGroups.map((timeSlotGroup, index) => (
        <HuTableRow
          key={`${timeSlotGroup.startTime}-${timeSlotGroup.endTime}-${timeSlotGroup.entries[0]?.start}-${timeSlotGroup.entries[0]?.end}`}
          sx={tableRowSx}
        >
          <HuTableCell colSpan={2}></HuTableCell>
          <HuTableCell>
            <TimeSlotInfo
              timeSlotWithEntries={timeSlotGroup}
              dayInfo={dayInfo}
            />
          </HuTableCell>
          <HuTableCell>
            <div>
              {displayHoursAndMinutes(timeSlotGroup.workedHours, false, true)}
            </div>
          </HuTableCell>
          <HuTableCell>
            <Stack sx={{ gap: 1 }}>
              {timeSlotGroup.entries.map(entry => (
                <EntriesTime
                  key={entry.pairId}
                  startTime={entry.start}
                  endTime={entry.end}
                  isNightShift={entry.isNightShift}
                />
              ))}
            </Stack>
          </HuTableCell>
          <HuTableCell>
            {showIncidencesOnExpandedRow && (
              <IncidenceSummary
                daySummary={dayInfo}
                incidenceTags={checkIncidencesOnSlot(timeSlotGroup, index)}
                groupWarningIncidences={false}
                isDeactivated={isDeactivated}
                containerSx={{
                  alignItems: 'center',
                  flexDirection: 'row',
                  gap: 1,
                  flexWrap: 'wrap',
                }}
              />
            )}
          </HuTableCell>
          <HuTableCell sx={STICKY_OPTIONS_CELL_SX} />
        </HuTableRow>
      ))}
    </>
  );
};

export default GroupSlots;
