import { useParams } from 'react-router-dom';
import TableForm from '../components/TableForm/TableForm';
import { useEffect, useRef, useState } from 'react';
import { TablesApi } from '../api/tables';
import { toast } from 'react-toastify';
import { createPortal } from 'react-dom';
import {
  NameTask,
  TaskInfoContainer,
} from '../components/common/SwitchFormTask/SwitchFormTask.style';
import { BackButton } from '../components/common/Buttons/BackButton';
import { useAuth } from '../app/context/AuthProvider';
import { connectToTable } from '../api/ws';

const TableInfo = ({ table }) => {
  if (!table) {
    return null;
  }

  const portalContent = (
    <TaskInfoContainer>
      <BackButton to={`/task/${table.task_id}`} />
      <NameTask>{table.name}</NameTask>
    </TaskInfoContainer>
  );

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

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

export default function TablePage() {
  const { tableId } = useParams();
  const [table, setTable] = useState(null);
  const [wsConnection, setWsConnection] = useState(null);
  const { user } = useAuth();
  const isUnmountingRef = useRef(false);

  useEffect(() => {
    if (!tableId) return;

    TablesApi.getTableInfo(Number(tableId))
      .then((data) => {
        if (data.result) {
          setTable(data.result);
        }
      })
      .catch(() => {
        toast.error('Ошибка получения информации о таблице');
      });
  }, [tableId]);

  useEffect(() => {
    if (!tableId || !user) return;

    const connection = connectToTable(tableId, user?.id, {
      onError: () => {
        toast.error('Ошибка подключения к серверу');
      },
      onClose: (event) => {
        if (isUnmountingRef.current) {
          return;
        }
        if (event.code !== 1000) {
          toast.warning(
            'Соединение с сервером потеряно. Изменения не будут синхронизироваться в реальном времени.',
          );
        }
      },
    });
    setWsConnection(connection);

    return () => {
      console.log('Отключение от WebSocket');
      isUnmountingRef.current = true;
      connection.disconnect();
    };
  }, [tableId, user]);

  if (!table) {
    return null;
  }

  return (
    <>
      <TableInfo table={table} />
    
    </>
  );
}
