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';

const TableInfo = ({ formId, sheetName }) => {
  const portalContent = (
    <TaskInfoContainer>
      <BackButton to={`/task/${formId}`} />
      {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 } = useParams();
  const { user } = useAuth();

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

    </>
  );
}
