import { type FC } from 'react';

import Chip from '@material-hu/mui/Chip';
import Stack from '@material-hu/mui/Stack';
import { type Theme } from '@material-hu/mui/styles';
import Typography from '@material-hu/mui/Typography';

import HuCardContainer from '@material-hu/components/design-system/CardContainer';

import { type TimeSlot } from 'src/types/timeTracking';

type Props = {
  name: string;
  programmedHoursText: string;
  timeSlots: TimeSlot[];
  nested?: boolean;
};

const MAX_CHIPS_PER_ROW = 3;

const chipSx = {
  background: ({ palette }: Theme) => palette.new.background.layout.tertiary,
  border: ({ palette }: Theme) =>
    `1px solid ${palette.new.border.neutral.default}`,
  typography: 'globalXXS',
  fontWeight: 'semiBold',
  color: ({ palette }: Theme) => palette.new.text.neutral.lighter,
  flexShrink: 0,
};

const ScheduleCard: FC<Props> = ({
  name,
  programmedHoursText,
  timeSlots,
  nested,
}) => (
  <HuCardContainer
    fullWidth
    sx={{
      backgroundColor: ({ palette }: Theme) =>
        nested
          ? palette.new.background.layout.tertiary
          : palette.new.background.layout.default,
      border: 'none',
    }}
  >
    <Stack
      sx={{
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        gap: 2,
      }}
    >
      <Stack sx={{ gap: 0.25, minWidth: 0, flex: 1 }}>
        <Typography
          variant="globalS"
          sx={{ fontWeight: 'bold' }}
        >
          {name}
        </Typography>
        <Typography
          variant="globalXXS"
          sx={{
            color: ({ palette }: Theme) => palette.new.text.neutral.lighter,
          }}
        >
          {programmedHoursText}
        </Typography>
      </Stack>
      {timeSlots.length > 0 && (
        <Stack
          sx={{
            display: 'grid',
            gridTemplateColumns: `repeat(${Math.min(timeSlots.length, MAX_CHIPS_PER_ROW)}, auto)`,
            gap: 0.5,
            justifyContent: 'flex-end',
          }}
        >
          {timeSlots.map(ts => (
            <Chip
              key={`${ts.startTime}-${ts.endTime}`}
              label={`${ts.startTime} - ${ts.endTime}`}
              size="small"
              sx={chipSx}
            />
          ))}
        </Stack>
      )}
    </Stack>
  </HuCardContainer>
);

export default ScheduleCard;
