import { useMemo, useState } from 'react';
import { useFormContext, useWatch } from 'react-hook-form';
import { useMatch } from 'react-router-dom';

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

import { FormDropTypes } from '@material-hu/components/deprecated/FormDrop/types';
import RoundedTabs from '@material-hu/components/deprecated/RoundedTabs';

import TaskLayout from 'src/pages/dashboard/Learning/Courses/New/components/TaskLayout';
import {
  FILE_MAX_SIZE as RECOMMENDED_FILE_MAX_SIZE,
  VIDEO_LESSON_MAX_SIZE,
} from 'src/pages/dashboard/Learning/Courses/New/constants';
import { newCourseFields } from 'src/pages/dashboard/Learning/Courses/New/forms';
import { coursesRoutes } from 'src/pages/dashboard/Learning/Courses/routes';
import {
  type Selected,
  type StepsTypes,
  VideoTypes,
} from 'src/pages/dashboard/Learning/Courses/types';
import { bytesToSize } from 'src/utils/filesUtils';
import { useLokaliseTranslation } from 'src/utils/i18n';

import FormDrop from 'src/components/FormInputs/FormDrop';
import FormYoutubeVideo from 'src/components/FormInputs/FormYoutubeVideo';

export type TaskVideoProps = {
  selected: Selected;
  disabled?: boolean;
};

export const TaskVideo = ({ selected, disabled = false }: TaskVideoProps) => {
  const { t } = useLokaliseTranslation('learning');
  const { setValue, control } = useFormContext<StepsTypes>();

  const isEdit = !!useMatch(coursesRoutes.editCourse());
  const isDuplicate = !!useMatch(coursesRoutes.duplicateCourse());

  const showPreview = isEdit || isDuplicate;

  const tasksName = newCourseFields.content.modules.tasks;

  const urlType = useWatch({
    name: tasksName.urlType(selected.module, selected.task),
    control,
  });

  const tabs = Object.values(VideoTypes).map(type => ({
    label: t(`course.video.type.${type.toLowerCase()}`),
    type,
  }));

  const [currentTabIndex, setCurrentTabIndex] = useState(
    tabs.findIndex(tab => tab.type === urlType),
  );

  const handleChangeTab = (_event: React.SyntheticEvent, value: number) => {
    setCurrentTabIndex(value);

    const newType = tabs[value].type;

    setValue(tasksName.urlType(selected.module, selected.task), newType);
    setValue(tasksName.video.all(selected.module, selected.task), {
      url: '',
      file: undefined,
    });
  };

  const inputByType = useMemo(
    () => ({
      [VideoTypes.INTERNAL]: (
        <Stack
          sx={{
            '& video': {
              objectFit: 'contain',
              aspectRatio: 'unset',
              maxHeight: '500px',
              backgroundColor: '#000',
            },
          }}
        >
          <FormDrop
            name={tasksName.video.all(selected.module, selected.task)}
            type={FormDropTypes.VIDEO}
            accept={{
              'video/mp4': [],
              'video/quicktime': ['.mov'],
            }}
            maxSize={VIDEO_LESSON_MAX_SIZE}
          />
          <Typography sx={{ color: '#676779' }}>
            •{' '}
            {t('course.lesson.video_limit_size', {
              size: bytesToSize(RECOMMENDED_FILE_MAX_SIZE),
            })}
          </Typography>
        </Stack>
      ),
      [VideoTypes.EXTERNAL]: (
        <FormYoutubeVideo
          name={tasksName.video.url(selected.module, selected.task)}
          disabled={disabled}
          showPreview={showPreview}
        />
      ),
    }),
    [selected, disabled, showPreview],
  );

  return (
    <TaskLayout.Container>
      <TaskLayout.Description
        disabled={disabled}
        selected={selected}
      />
      <TaskLayout.Content>
        <Stack
          sx={{
            gap: 3,
            '& > .MuiBox-root': { m: 0 },
          }}
        >
          <RoundedTabs
            tabs={tabs}
            tabIndex={currentTabIndex}
            onChange={handleChangeTab}
          />
          {inputByType[tabs[currentTabIndex].type]}
        </Stack>
      </TaskLayout.Content>
      <TaskLayout.Attachments
        selected={selected}
        disabled={disabled}
      />
    </TaskLayout.Container>
  );
};

export default TaskVideo;
