import { useWatch } from 'react-hook-form';

import Box from '@material-hu/mui/Box';
import Stack from '@material-hu/mui/Stack';
import { useTheme } from '@material-hu/mui/styles';
import Typography from '@material-hu/mui/Typography';

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

import { type ShiftColor } from 'src/types/shifts';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { calculateTimeSpanInHours } from 'src/utils/timeTracking';

import {
  type RotationDay,
  type ShiftRotationFormData,
  shiftRotationFormFields,
} from '../../../form';
import { SHIFT_CARD_COLORS } from '../../ShiftsTable/constants';

type SummaryRow = {
  label: string;
  value: string;
};

const DAY_BOX_WIDTH = 40;
const DAY_BOX_MAX_HEIGHT = 35;

type DayBoxProps = {
  day: RotationDay;
};

const DayBox = ({ day }: DayBoxProps) => {
  const { palette } = useTheme();
  const colorMap = SHIFT_CARD_COLORS(palette);

  const bars: {
    key: string;
    backgroundColor?: string;
    borderColor?: string;
  }[] =
    day.type === 'shift' && day.shifts?.length
      ? day.shifts.map(shift => {
          const colors = colorMap[(shift.color as ShiftColor) ?? 'dayOff'];
          return {
            key: `shift-${shift.id}`,
            backgroundColor: colors.backgroundColor,
            borderColor: colors.accentBorderColor,
          };
        })
      : [
          {
            key: 'rest',
            backgroundColor: palette.new.background.elements.grey,
            borderColor: palette.new.border.neutral.default,
          },
        ];

  return (
    <Stack
      sx={{
        width: DAY_BOX_WIDTH,
        height: DAY_BOX_MAX_HEIGHT,
        maxHeight: DAY_BOX_MAX_HEIGHT,
        gap: 0.5,
      }}
    >
      {bars.map(bar => (
        <Box
          key={bar.key}
          sx={{
            flex: 1,
            backgroundColor: bar.backgroundColor,
            border: '1px solid',
            borderColor: bar.borderColor,
            borderRadius: '6px',
          }}
        />
      ))}
    </Stack>
  );
};

const RotationSummary = () => {
  const { t } = useLokaliseTranslation('shifts');
  const { palette } = useTheme();

  const days =
    useWatch<ShiftRotationFormData, typeof shiftRotationFormFields.days>({
      name: shiftRotationFormFields.days,
    }) ?? [];

  const cycleDuration = days.length;
  const totalShifts = days.reduce(
    (acc, day) => acc + (day.shifts?.length ?? 0),
    0,
  );
  const restDays = days.filter(day => day.type === 'rest').length;
  const workHours = Math.round(
    days.reduce(
      (acc, day) =>
        acc +
        (day.shifts ?? []).reduce(
          (shiftAcc, shift) =>
            shiftAcc +
            shift.timeSlots.reduce(
              (slotAcc, slot) =>
                slotAcc +
                calculateTimeSpanInHours(slot.startTime, slot.endTime),
              0,
            ),
          0,
        ),
      0,
    ),
  );

  const rows: SummaryRow[] = [
    {
      label: t('templates.resume.duration'),
      value: t('templates.resume.duration_count', { count: cycleDuration }),
    },
    {
      label: t('templates.resume.shifts'),
      value: String(totalShifts),
    },
    {
      label: t('templates.resume.rest_days'),
      value: String(restDays),
    },
    {
      label: t('templates.resume.work_hours'),
      value: String(workHours),
    },
  ];

  return (
    <CardContainer fullWidth>
      <Stack sx={{ gap: 0.5 }}>
        <Typography
          variant="globalM"
          sx={{ fontWeight: 'fontWeightSemiBold' }}
        >
          {t('templates.resume.title')}
        </Typography>
        <Typography
          variant="globalS"
          sx={{ color: palette.new.text.neutral.lighter }}
        >
          {t('templates.resume.description')}
        </Typography>
      </Stack>

      {days.length > 0 && (
        <Stack
          sx={{
            flexDirection: 'row',
            flexWrap: 'wrap',
            gap: 1,
            mt: 2,
          }}
        >
          {days.map(day => (
            <DayBox
              key={day.id}
              day={day}
            />
          ))}
        </Stack>
      )}

      <Stack sx={{ gap: 1, mt: 3 }}>
        {rows.map(row => (
          <Stack
            key={row.label}
            sx={{
              justifyContent: 'space-between',
            }}
          >
            <Typography
              variant="globalS"
              sx={{ color: palette.new.text.neutral.lighter }}
            >
              {row.label}
            </Typography>
            <Typography
              variant="globalS"
              sx={{ fontWeight: 'fontWeightSemiBold' }}
            >
              {row.value}
            </Typography>
          </Stack>
        ))}
      </Stack>
    </CardContainer>
  );
};

export default RotationSummary;
