import { memo } from 'react';

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

import { type JourneyTaskDetail, JourneyTaskType } from '../../../types';
import {
  DocumentUploadSection,
  type UploadedDocument,
} from '../DocumentUploadSection';

import { TaskAttachments } from './TaskAttachments';
import { TaskBody } from './TaskBody';
import { TaskInformation } from './TaskInformation';

const noop = () => {};

const isDocumentTask = (
  task: JourneyTaskDetail | undefined,
): task is Extract<
  JourneyTaskDetail,
  { task: { type: JourneyTaskType.DOCUMENT } }
> => task?.task?.type === JourneyTaskType.DOCUMENT;

type TaskProps = {
  task?: JourneyTaskDetail;
  isLoading: boolean;
  onDocumentFilesChange?: (files: UploadedDocument[]) => void;
  onViewDocuments?: () => void;
  showDocumentErrors?: boolean;
};

export const Task = memo(
  ({
    task,
    isLoading,
    onDocumentFilesChange,
    onViewDocuments,
    showDocumentErrors,
  }: TaskProps) => {
    const isTaskDone = task?.status === 'DONE';

    return (
      <Stack sx={{ gap: 2 }}>
        <TaskInformation
          task={task}
          isLoading={isLoading}
        />
        <TaskBody
          task={task}
          isLoading={isLoading}
        />
        <TaskAttachments attachments={task?.task?.attachments || []} />
        {isDocumentTask(task) && !isLoading && (
          <DocumentUploadSection
            documentNames={task.task.documentNames}
            isCompleted={isTaskDone}
            onFilesChange={onDocumentFilesChange ?? noop}
            onViewDocuments={onViewDocuments}
            showValidationErrors={showDocumentErrors}
            uploadedDocuments={task.taskInfo.documents}
          />
        )}
      </Stack>
    );
  },
  (prevProps, nextProps) => {
    return (
      prevProps.task === nextProps.task &&
      prevProps.isLoading === nextProps.isLoading &&
      prevProps.onDocumentFilesChange === nextProps.onDocumentFilesChange &&
      prevProps.onViewDocuments === nextProps.onViewDocuments &&
      prevProps.showDocumentErrors === nextProps.showDocumentErrors
    );
  },
);

Task.displayName = 'Task';
