import { FC } from 'react';
import { useFormContext, useWatch } from 'react-hook-form';

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

import { SxProps } from '@material-hu/mui/styles';

import SelectionCard from '@material-hu/components/composed-components/SelectionCard';
import RadioButton from '@material-hu/components/design-system/RadioButton/RadioButton';

import { RadioOption } from 'src/types/timeTracking';

type Props = {
  name: string;
  options: RadioOption[];
  sx?: SxProps;
};

const RadioGroupWithChildren: FC<Props> = props => {
  const { name, options, sx } = props;
  const { control, setValue } = useFormContext();
  const selectedValue = useWatch({ control, name });

  return (
    <Stack sx={{ flexDirection: 'column', gap: 2, ...sx }}>
      {options.map(({ value, label, helperText, children }) => {
        const isSelected = selectedValue === value;
        return (
          <SelectionCard
            key={String(value)}
            fullWidth
            checked={isSelected}
            onClick={() =>
              setValue(name, value, { shouldDirty: true, shouldTouch: true })
            }
            sx={{
              backgroundColor: (theme: Theme) =>
                `${theme.palette.new.background.layout.tertiary} !important`,
              borderColor: (theme: Theme) =>
                `${theme.palette.new.border.neutral.default || theme.palette.divider} !important`,
            }}
          >
            <Stack sx={{ gap: 2 }}>
              <RadioButton
                isActive={isSelected}
                label={String(label ?? '')}
                description={helperText}
                stackSx={{ gap: 1 }}
              />
              {isSelected && (
                <Stack
                  onClick={e => e.stopPropagation()}
                  onMouseDown={e => e.stopPropagation()}
                >
                  {children}
                </Stack>
              )}
            </Stack>
          </SelectionCard>
        );
      })}
    </Stack>
  );
};

export default RadioGroupWithChildren;
