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

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

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

import { LearningCard } from 'src/pages/dashboard/Learning/common/components/LearningCard';
import { useSessionStatus } from 'src/pages/dashboard/Learning/Sessions/hooks/useSessionStatus';
import { type NewSessionFormValues } from 'src/pages/dashboard/Learning/Sessions/types';

const SEND_NOTIFICATION_FIELD = 'configuration.sendNotification';

type SessionSelectionCardsProps = {
  title: string;
  name: 'configuration.sendNotification' | 'configuration.isObligatory';
  options: {
    label: string;
    description: string;
    value: boolean;
  }[];
};

export const SessionSelectionCards = ({
  title,
  options,
  name,
}: SessionSelectionCardsProps) => {
  const { blockSessionEdition, blockNotificationsEdition } = useSessionStatus();
  const { control, setValue } = useFormContext<NewSessionFormValues>();

  const value = useWatch({ name, control });

  const isNotificationsField = name === SEND_NOTIFICATION_FIELD;
  const isDisabled =
    blockSessionEdition || (isNotificationsField && blockNotificationsEdition);

  useEffect(() => {
    if (isNotificationsField && blockNotificationsEdition && value !== false) {
      setValue(SEND_NOTIFICATION_FIELD, false);
    }
  }, [isNotificationsField, blockNotificationsEdition, value]);

  return (
    <LearningCard id={`session-configuration-${title}-card`}>
      <Title
        variant="S"
        title={title}
      />
      <Stack sx={{ flexDirection: 'row', gap: 2, width: '100%' }}>
        {options.map(option => {
          const isChecked = value === option.value;
          return (
            <SelectionCard
              key={option.label}
              sx={{
                flex: 1,
                '& *': {
                  userSelect: isDisabled ? 'none' : 'auto',
                },
                ...(isDisabled &&
                  isChecked && {
                    outline: '2px solid',
                    outlineColor: 'primary.main',
                    backgroundColor: 'action.selected',
                  }),
              }}
              checked={isChecked}
              onClick={() => setValue(name, option.value)}
              disabled={isDisabled}
            >
              <RadioButton
                disabled={isDisabled && !isChecked}
                label={option.label}
                description={option.description}
                isActive={isChecked}
              />
            </SelectionCard>
          );
        })}
      </Stack>
    </LearningCard>
  );
};
