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

import PdfViewer from '@material-hu/components/composed-components/PdfViewer';

import { type ReadingTask } from '../../types';

import TaskHTML from './TaskHTML';

type TaskReadingProps = {
  task: ReadingTask;
};

const TaskReading = ({ task }: TaskReadingProps) => {
  const { setValue } = useFormContext();

  const markFinished = useCallback(
    () => setValue('multimediaFinished', true),
    [setValue],
  );

  useEffect(() => {
    if (task.body) markFinished();
  }, [task.body, markFinished]);

  if (task.body) return <TaskHTML body={task.body} />;

  if (!task.url) return null;

  return (
    <PdfViewer
      file={task.url}
      onFinishRead={markFinished}
    />
  );
};

export default TaskReading;
