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

import { type TablerIcon } from '@material-hu/icons/tabler';
import Stack from '@material-hu/mui/Stack';
import useTheme from '@material-hu/mui/styles/useTheme';
import Typography from '@material-hu/mui/Typography';

import MenuList from '@material-hu/components/composed-components/MenuList';
import HuSelectionCard from '@material-hu/components/composed-components/SelectionCard';

import { type Shift } from 'src/types/shifts';
import { setTimeString } from 'src/utils/date';
import { useLokaliseTranslation } from 'src/utils/i18n';
import {
  calculateTimeSpanInHours,
  parseHoursAndMinutesDisplay,
} from 'src/utils/timeTracking';

import EllipsisTooltip from 'src/components/EllipsisTooltip';

import { COLOR_OPTIONS } from '../../constants';
import { type ShiftFormData } from '../../form';
import {
  GLOBAL_XXS_TYPOGRAPHY_SX,
  SHIFT_CARD_COLORS,
} from '../ShiftsTable/constants';

type CardOption = {
  title: string;
  Icon: TablerIcon;
  onClick: () => void;
};

type Props = {
  shift: Shift;
  onCustomShiftPrefill?: (name: string) => void;
  isDeletingShiftTemplate?: boolean;
  getCardOptions: (shift: Shift) => CardOption[];
};

const TemplateCard = ({
  shift,
  onCustomShiftPrefill,
  isDeletingShiftTemplate = false,
  getCardOptions,
}: Props) => {
  const { t } = useLokaliseTranslation([
    'shifts',
    'time_tracker',
    'time_tracking_common',
  ]);
  const theme = useTheme();
  const form = useFormContext<ShiftFormData>();

  const isAssigningShift = Boolean(onCustomShiftPrefill);

  const handleShiftPrefill = () => {
    const shiftColor = COLOR_OPTIONS.find(color => color.value === shift.color);
    const shiftTimeSlots = shift.timeSlots.map(timeSlot => ({
      id: timeSlot.id,
      startTime: timeSlot.startTime
        ? setTimeString(new Date(), timeSlot.startTime)
        : null,
      endTime: timeSlot.endTime
        ? setTimeString(new Date(), timeSlot.endTime)
        : null,
    }));
    // Form values are reset to simplify the logic to check if the template values were modified
    form.reset({
      ...form.getValues(),
      shiftName: shift.name,
      color: shiftColor?.value,
      timeSlots: shiftTimeSlots,
      notes: shift.description,
    });
    onCustomShiftPrefill?.(shift.name);
  };

  const totalShiftsDuration = shift.timeSlots.reduce(
    (acc, timeSlot) =>
      acc + calculateTimeSpanInHours(timeSlot.startTime, timeSlot.endTime),
    0,
  );
  const programmedText = t('time_tracker:scheduled_f', {
    count: totalShiftsDuration,
  });
  const programmedHoursDisplay = `${t(...parseHoursAndMinutesDisplay(totalShiftsDuration, false))} ${programmedText}`;

  return (
    <HuSelectionCard
      checked={false}
      // If HuSelectioncard has onClick defined it will wrapped in a button, so this conditional prop
      // is done to avoid the DOM error when nesting a button inside of another (icon button nested in card)
      {...(isAssigningShift && { onClick: handleShiftPrefill })}
      sx={{
        borderRadius: theme.shape.borderRadiusM,
        borderColor: `${SHIFT_CARD_COLORS(theme.palette)[shift.color ?? 'dayOff'].accentBorderColor} !important`,
        '& .MuiCardContent-root': {
          alignItems: 'center',
          display: 'flex',
          flexDirection: 'row',
          justifyContent: 'space-between',
          px: 1.5,
          py: 1,
        },
      }}
      fullWidth
    >
      <Stack sx={{ maxWidth: '50%' }}>
        <EllipsisTooltip title={shift.name || t('time_tracker:unnamed_shift')}>
          <Typography
            variant="globalS"
            sx={{
              ...GLOBAL_XXS_TYPOGRAPHY_SX,
              fontWeight: 'fontWeightSemiBold',
            }}
            noWrap
          >
            {shift.name || t('time_tracker:unnamed_shift')}
          </Typography>
        </EllipsisTooltip>
        {!shift.timeSlots.length && (
          <Typography
            variant="globalS"
            sx={GLOBAL_XXS_TYPOGRAPHY_SX}
          >
            {t('integration_shift')}
          </Typography>
        )}
        {shift.timeSlots.length > 0 &&
          shift.timeSlots.map(timeSlot => (
            <Typography
              key={timeSlot.startTime}
              variant="globalS"
              sx={GLOBAL_XXS_TYPOGRAPHY_SX}
            >
              {`${timeSlot.startTime} - ${timeSlot.endTime}`}
            </Typography>
          ))}
      </Stack>
      <Stack sx={{ flexDirection: 'row', alignItems: 'center', gap: 1 }}>
        <Typography variant="globalS">{programmedHoursDisplay}</Typography>
        {!isAssigningShift && (
          <MenuList
            size="small"
            position="left"
            disableMenu={isDeletingShiftTemplate}
            options={getCardOptions(shift)}
          />
        )}
      </Stack>
    </HuSelectionCard>
  );
};

export default TemplateCard;
