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

import { useModal } from '@material-hu/hooks/useModal';
import ButtonBase from '@material-hu/mui/ButtonBase';
import Grid from '@material-hu/mui/Grid';
import Paper from '@material-hu/mui/Paper';
import Stack from '@material-hu/mui/Stack';
import { useTheme } from '@material-hu/mui/styles';
import Typography from '@material-hu/mui/Typography';

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

import useCommunityFeature from 'src/hooks/useCommunityFeature';
import PremiumModal from 'src/pages/dashboard/Learning/Courses/New/components/PremiumModal';
import {
  TASK_DEFAULT_VALUES,
  TASKS_ICONS,
  VIDEO_LESSON_MAX_SIZE,
} from 'src/pages/dashboard/Learning/Courses/New/constants';
import { newCourseFields } from 'src/pages/dashboard/Learning/Courses/New/forms';
import {
  type Selected,
  TaskTypes,
} from 'src/pages/dashboard/Learning/Courses/types';
import { CommunityFeature } from 'src/types/communityFeatures';
import { bytesToSize } from 'src/utils/filesUtils';
import { useLokaliseTranslation } from 'src/utils/i18n';

import SeverityPill, { Severities } from 'src/components/SeverityPill';

export type TaskNewProps = {
  disabled?: boolean;
  selected: Selected;
  onSelectType?: (type: TaskTypes) => void;
};

export const TaskNew = ({
  disabled = false,
  selected,
  onSelectType = () => null,
}: TaskNewProps) => {
  const theme = useTheme();
  const { t } = useLokaliseTranslation('learning');
  const { setValue, getValues } = useFormContext();
  const canManageScorm = useCommunityFeature(CommunityFeature.VIEW_SCORMS_V2);

  const { modal: premiumModal, showModal: showPremiumModal } = useModal(
    PremiumModal,
    {
      maxWidth: 'xs',
      fullWidth: true,
    },
  );

  const handleSelectType = (type: TaskTypes) => () => {
    const taskName = newCourseFields.content.modules.tasks.detail(
      selected.module,
      selected.task,
    );

    const task = getValues(taskName);

    setValue(taskName, {
      ...task,
      type,
      title: task.title || t('course.lesson.title_placeholder'),
      ...TASK_DEFAULT_VALUES[type],
    });

    onSelectType(type);
  };

  const handlePremiumClick = (type: TaskTypes) => () =>
    showPremiumModal({ type });

  const segments = [
    {
      title: t('course.lesson.content_label'),
      options: [
        {
          type: TaskTypes.VIDEO,
          title: t('course.lesson.type.video'),
          description: t('course.lesson.type_description.video', {
            max: bytesToSize(VIDEO_LESSON_MAX_SIZE),
          }),
          icon: TASKS_ICONS[TaskTypes.VIDEO],
        },
        {
          type: TaskTypes.READING,
          title: t('course.lesson.type.reading'),
          description: t('course.lesson.type_description.reading'),
          icon: TASKS_ICONS[TaskTypes.READING],
        },
        {
          type: TaskTypes.BLANK,
          title: t('course.lesson.type.lesson'),
          description: t('course.lesson.type_description.article'),
          icon: TASKS_ICONS[TaskTypes.BLANK],
        },
        {
          type: TaskTypes.SCORM,
          title: t('course.lesson.type.scorm'),
          description: t('course.lesson.type_description.scorm'),
          icon: TASKS_ICONS[TaskTypes.SCORM],
          isPremium: true,
          hasPermissions: canManageScorm,
        },
      ],
    },
    {
      title: t('course.lesson.evaluation_label'),
      options: [
        {
          type: TaskTypes.QUESTIONNAIRE,
          title: t('course.lesson.type.evaluation'),
          description: t('course.lesson.type_description.evaluation'),
          icon: TASKS_ICONS[TaskTypes.QUESTIONNAIRE],
        },
      ],
    },
  ];

  return (
    <>
      {premiumModal}
      <Stack sx={{ gap: 5 }}>
        {segments.map(segment => (
          <Stack
            key={segment.title}
            sx={{ gap: 2 }}
          >
            <Typography variant="subtitle1">{segment.title}</Typography>
            <Grid
              container
              rowSpacing={2}
              columnSpacing={4}
            >
              {segment.options.map(
                ({
                  type,
                  title,
                  description,
                  icon: { Icon: OptionIcon, color: optionColor },
                  isPremium = false,
                  hasPermissions = true,
                }) => (
                  <Grid
                    item
                    key={type}
                    xs={12}
                    lg={6}
                  >
                    <Paper
                      elevation={24}
                      component={!hasPermissions ? ButtonBase : 'div'}
                      onClick={
                        !hasPermissions ? handlePremiumClick(type) : undefined
                      }
                      sx={{
                        display: 'flex',
                        flexDirection: 'column',
                        justifyContent: 'flex-start',
                        borderRadius: '20px',
                        gap: 1,
                        p: 3,
                        pt: 4,
                        width: '100%',
                        height: '100%',
                        '& > *': {
                          width: '100%',
                        },
                      }}
                    >
                      <Stack sx={{ gap: 1, flexDirection: 'row' }}>
                        <Stack
                          sx={{ gap: 1, flexDirection: 'row', mr: 'auto' }}
                        >
                          <OptionIcon
                            sx={{ color: optionColor, fontSize: '40px' }}
                          />
                          <Typography
                            variant="h6"
                            sx={{
                              display: 'flex',
                              alignItems: 'center',
                              pb: '4px',
                              mr: 'auto',
                            }}
                          >
                            {title}
                          </Typography>
                        </Stack>
                        {isPremium && (
                          <SeverityPill
                            label={t('general:add_on')}
                            severity={Severities.RECOMMENDED}
                          />
                        )}
                      </Stack>
                      <Stack sx={{ gap: 2, flexDirection: 'row' }}>
                        <Typography
                          variant="body2"
                          sx={{
                            color: theme.palette.text.secondary,
                            mr: hasPermissions ? 'auto' : '64px',
                            minHeight: '42.5px',
                            textAlign: 'left',
                          }}
                        >
                          {description}
                        </Typography>
                        {hasPermissions && (
                          <Button
                            variant="text"
                            disabled={disabled}
                            onClick={handleSelectType(type)}
                          >
                            {t('general:add')}
                          </Button>
                        )}
                      </Stack>
                    </Paper>
                  </Grid>
                ),
              )}
            </Grid>
          </Stack>
        ))}
      </Stack>
    </>
  );
};

export default TaskNew;
