import { createPortal } from 'react-dom';
import {
  NameTask,
  TaskInfoContainer,
} from '../components/common/SwitchFormTask/SwitchFormTask.style';
import RealtimeTable from '../components/RealtimeTable';
import { useParams } from 'react-router-dom';
import { RealtimeProvider } from '../components/RealtimeTable/contexts/RealtimeContext';
import { useAuth } from '../app/context/AuthProvider';
import { BackButton } from '../components/common/Buttons/BackButton';
import { SHEET_NAME } from '../constants/constants';

const TableInfo = ({ formId, sheetName, isProject = false }) => {
  const path = (isProject ? `/project/` : '/task/') + formId;
  const portalContent = (
    <TaskInfoContainer>
      <BackButton to={path} />
      {sheetName && (
        <NameTask>{SHEET_NAME[sheetName] || sheetName}</NameTask>
      )}
    </TaskInfoContainer>
  );

  const targetElement = document.getElementById('TableInfo');

  if (targetElement) {
    return createPortal(portalContent, targetElement);
  }
};

export default function NewTablePage() {
  const { formId, formType, sheetName, direction, year } = useParams();
  const { user } = useAuth();
  const isProject = formType == 'PROJECT';

  return (
    <>
      {formId && <TableInfo formId={formId} sheetName={sheetName} isProject={isProject} />}
      {user && (
        <RealtimeProvider
          formId={formId}
          sheetName={sheetName}
          userId={user.id}
          direction={direction === 'null' ? null : direction}
          isProject={isProject}
          year={year}
        >
          <RealtimeTable
            formType={formType}
            formId={formId}
            sheetName={sheetName}
            direction={direction === 'null' ? null : direction}
            year={year}
          />
        </RealtimeProvider>
      )}

    </>
  );
}
