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

import Alert from '@material-hu/mui/Alert';
import AlertTitle from '@material-hu/mui/AlertTitle';
import Divider from '@material-hu/mui/Divider';
import Link from '@material-hu/mui/Link';
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 PlusIcon from 'src/icons/Plus';
import {
  TASKS_ICONS,
  TITLE_MAX_LENGTH,
  TITLE_MIN_LENGTH,
} from 'src/pages/dashboard/Learning/Courses/New/constants';
import { newCourseFields } from 'src/pages/dashboard/Learning/Courses/New/forms';
import { validateTask } from 'src/pages/dashboard/Learning/Courses/New/utils';
import {
  type Selected,
  type Task,
} from 'src/pages/dashboard/Learning/Courses/types';
import { useLokaliseTranslation } from 'src/utils/i18n';

import FormClickableTextField from 'src/components/FormInputs/FormClickableTextField';
import FormImageMenu from 'src/components/FormInputs/FormImageMenu';

export type ContentModuleProps = {
  disabled?: boolean;
  selected: Selected;
  showInfoAlert?: boolean;
  onCloseInfoAlert?: () => void;
  onCreateTask?: (module: number) => void;
  onSelect?: (newSelected: Selected) => void;
};

export const ContentModule = ({
  disabled = false,
  selected,
  showInfoAlert = false,
  onCloseInfoAlert = () => null,
  onCreateTask = () => null,
  onSelect = () => null,
}: ContentModuleProps) => {
  const { t } = useLokaliseTranslation('learning');
  const theme = useTheme();

  const moduleName = newCourseFields.content.modules.detail(selected.module);
  const tasksName = newCourseFields.content.modules.tasks.all(selected.module);

  const { control, watch } = useFormContext();

  const module = watch(moduleName);

  useFieldArray({
    control,
    name: tasksName,
  });

  const handleCreateTask = () => onCreateTask(selected.module);

  const handleSelect =
    (task: number = -1) =>
    () =>
      onSelect({ module: selected.module, task });

  const handleCloseInfoAlert = () => onCloseInfoAlert();

  const isDefaultTitle = module.title === t('course.lesson.title_placeholder');

  return (
    <Stack
      sx={{
        gap: 2,
        width: '100%',
        p: 3,
        maxWidth: '900px',
      }}
    >
      {showInfoAlert && (
        <Alert
          onClose={handleCloseInfoAlert}
          color="info"
        >
          <AlertTitle>{t('course.how_to_create_content')}</AlertTitle>
          {t('course.how_to_create_content_description')}
        </Alert>
      )}
      <Stack sx={{ borderRadius: '20px', gap: 2, p: 3 }}>
        <Stack sx={{ justifyContent: 'center', alignItems: 'center' }}>
          <Stack sx={{ width: '100%' }}>
            <Stack sx={{ alignItems: 'center', flexDirection: 'row', gap: 3 }}>
              <FormImageMenu
                key={newCourseFields.content.modules.icon(selected.module)}
                name={newCourseFields.content.modules.icon(selected.module)}
                disabled={disabled}
                width={400}
                withArrow={false}
                sx={{ mb: '20px' }}
              />
              <FormClickableTextField
                key={newCourseFields.content.modules.title(selected.module)}
                name={newCourseFields.content.modules.title(selected.module)}
                disabled={disabled}
                resetOnEmptyBlur
                blurOnEnter
                valueAsPlaceholder={isDefaultTitle}
                showCounter
                maxLength={TITLE_MAX_LENGTH}
                maxLengthError={t('course.title_max_length', {
                  count: TITLE_MAX_LENGTH,
                })}
                minLength={TITLE_MIN_LENGTH}
                minLengthError={t('course.title_min_length', {
                  count: TITLE_MIN_LENGTH,
                })}
                inputProps={{
                  sx: {
                    fontSize: '24px',
                    fontWeight: 700,
                    mt: -1,
                  },
                }}
                typographyProps={{ variant: 'h5' }}
              />
            </Stack>
            <Divider sx={{ mt: '-10px' }} />
          </Stack>
          {module?.tasks?.length === 0 && (
            <>
              <Stack
                sx={{
                  justifyContent: 'center',
                  alignItems: 'center',
                  gap: 1,
                  my: 5,
                }}
              >
                <Typography variant="h6">
                  {t('course.lesson.no_lessons_created')}
                </Typography>
                <Typography variant="body1">
                  {t('course.lesson.no_lessons_created_description')}
                </Typography>
              </Stack>
              <Button
                id="add-task-content-button"
                startIcon={<PlusIcon />}
                variant="outlined"
                onClick={handleCreateTask}
                disabled={disabled}
              >
                {t('course.lesson.add')}
              </Button>
            </>
          )}
          {module.tasks.length > 0 && (
            <Stack
              sx={{
                gap: 2,
                mt: 3,
                pl: 2,
                width: '100%',
                alignItems: 'flex-start',
              }}
            >
              {module?.tasks?.map((task: Task, taskIndex: number) => {
                const { Icon, color } =
                  TASKS_ICONS[task.type as keyof typeof TASKS_ICONS];

                const isIncomplete = !validateTask(task);

                return (
                  <Stack
                    key={task.id}
                    sx={{
                      gap: 0.5,
                      flexDirection: 'row',
                      alignItems: 'center',
                    }}
                  >
                    <Icon sx={{ color, fontSize: '16px' }} />
                    <Link
                      component="button"
                      variant="body2"
                      underline="always"
                      sx={{
                        color: isIncomplete
                          ? theme.palette.warning.dark
                          : theme.palette.secondary.main,
                        textDecorationColor: isIncomplete
                          ? theme.palette.warning.dark
                          : theme.palette.secondary.main,
                      }}
                      onClick={handleSelect(taskIndex)}
                    >
                      <Stack
                        sx={{
                          alignItems: 'center',
                          flexDirection: 'row',
                          gap: 0.5,
                        }}
                      >
                        {task.title}
                        {isIncomplete && (
                          <Stack
                            sx={{
                              width: '8px',
                              height: '8px',
                              borderRadius: '50%',
                              backgroundColor: theme.palette.warning.dark,
                            }}
                          />
                        )}
                      </Stack>
                    </Link>
                  </Stack>
                );
              })}
              <Button
                startIcon={<PlusIcon />}
                variant="text"
                onClick={handleCreateTask}
                sx={{ py: 0, ml: '-16px' }}
              >
                {t('course.lesson.add')}
              </Button>
            </Stack>
          )}
        </Stack>
      </Stack>
    </Stack>
  );
};

export default ContentModule;
