import { useEffect, useState } from 'react';
import { createPortal } from 'react-dom';
import {
  TaskInfoContainer,
  NameTask,
} from '../../components/common/SwitchFormTask/SwitchFormTask.style';
import { EditSvg } from '../../components/common/icons/icons';
import { IconButton, Button, TextField, Typography } from '@mui/material';
import Modal from '../../components/common/Modal/Modal';
import { TablesApi } from '../../api/tables';
import { toast } from 'react-toastify';
import { BackButton } from '../../components/common/Buttons/BackButton';

export function InfoForHeader({ table }) {
  const [openModalRename, setOpenModalRename] = useState(false);
  const [curTable, setCurTable] = useState();

  useEffect(() => {
    if (!table) return;
    setCurTable(table);
  }, [table]);

  const handleClickOpenRename = () => {
    setOpenModalRename(true);
  };
  const handleCloseRename = () => {
    setOpenModalRename(false);
  };
  const handleUpdateTableInfo = (name) => {
    curTable.name = name;
    TablesApi.updateTemplateInfo(curTable.id, curTable)
      .then((data) => {
        if (data.result) {
          setCurTable(data.result);
        }
      })
      .catch(() => {
        toast.error('Ошибка при переименование таблицы');
      });
    handleCloseRename();
  };
  if (!curTable) return;

  const ModalRename = ({ table, open, onClose }) => {
    const [name, setName] = useState(table.name);
    return (
      <Modal
        open={open}
        onClose={onClose}
        title={'Переименовать таблицу'}
        actions={
          <>
            <Button
              variant="grey"
              onClick={handleCloseRename}
              style={{ height: '2.5rem' }}
            >
              Отменить
            </Button>
            <Button
              variant="contained"
              onClick={() => {
                handleUpdateTableInfo(name);
              }}
              style={{ height: '2.5rem' }}
            >
              Переименовать
            </Button>
          </>
        }
      >
        <Typography
          sx={{
            fontWeight: '400',
            fontSize: '0.88rem',
            color: '#4a5565',
            lineHeight: '1.2',
          }}
        >
          Название
        </Typography>

        <TextField
          variant="outlined"
          placeholder="Введите название"
          value={name}
          onChange={(e) => setName(e.target.value)}
          size="small"
          sx={{
            width: '100%',
            '& .MuiOutlinedInput-root': {
              height: '2rem',
              fontSize: '0.875rem',
              '& fieldset': {
                borderRadius: '0.5rem',
                border: '1px solid rgba(0,0,0,0.1)',
              },
            },
            '& .MuiInputBase-input': {
              padding: '0 0.875rem',
              height: '100%',
            },
          }}
        />
      </Modal>
    );
  };
  const portalContent = (
    <>
      <TaskInfoContainer>
        <BackButton
          to={curTable?.form_id ? `/form/${curTable.form_id}` : '/forms'}
        />
        <NameTask>{curTable.name}</NameTask>
        <IconButton
          onClick={handleClickOpenRename}
          sx={{
            margin: '0.25rem',
            padding: 0,
            width: '1.5rem',
            height: '1.5rem',
            border: '.0625rem solid var(--Stroke, rgba(0, 0, 0, 0.1))',
            borderRadius: '.5rem',
            background: 'var(--White, rgba(255, 255, 255, 1))',
            ':hover': {
              backgroundColor: 'inherit',
            },
          }}
        >
          <EditSvg size={'.75rem'}></EditSvg>
        </IconButton>
      </TaskInfoContainer>
      <ModalRename
        table={curTable}
        open={openModalRename}
        onClose={handleCloseRename}
      />
    </>
  );
  const targetElement = document.getElementById('TableInfo');
  if (targetElement) {
    return createPortal(portalContent, targetElement);
  }
}
