import { useEffect, useMemo, useState } from 'react';
import {
  MaterialReactTable,
  useMaterialReactTable,
} from 'material-react-table';
import {
  Box,
  Typography,
  IconButton,
  TextField,
  Autocomplete,
} from '@mui/material';
import { CheckIcon, CheckedIcon } from '../IconsForTable/icons';
import { TrashSvg } from '../../../components/common/icons/icons';
import { ROLES_NAME_ID } from '../../../constants';

const StyleForChecked = {
  display: 'flex',
  alignItems: 'center',
  justifyContent: 'flex-start',
  cursor: 'pointer',
  '& svg': {
    width: '1rem',
    height: '1rem',
  },
  '&:hover': {
    opacity: 0.8,
  },
};

const UserTableForAdd = ({
  usersEmail = [],
  sspOptions = [],
  onDeleteUser,
  onChangeUsers,
}) => {
  const [allUsers, setAllUsers] = useState([]);

  useEffect(() => {
    const emailUsers = usersEmail.map((email) => ({
      id: email,
      email: email,
      ssp: '',
      admin: false,
      executor_dfip: false,
      executor_rf: false,
      username: email.split('@')[0],
      ssp_id: null,
    }));

    setAllUsers((prev) => [...prev, ...emailUsers]);
  }, [usersEmail]);

  const handleRoleChange = (userId, role) => {
    const allRoles = Object.fromEntries(
      Object.keys(ROLES_NAME_ID).map((key) => [key, false]),
    );
    allRoles[role] = true;
    setAllUsers((prev) =>
      prev.map((user) =>
        user.id === userId
          ? { ...user, ...allRoles, role_id: ROLES_NAME_ID[role] }
          : user,
      ),
    );
  };

  const handleSspChange = (userId, ssp) => {
    setAllUsers((prev) =>
      prev.map((user) =>
        user.id === userId
          ? {
              ...user,
              ssp: ssp,
              ssp_id: ssp.id,
            }
          : user,
      ),
    );
  };

  const handleDeleteUser = (userId) => {
    setAllUsers((prev) => prev.filter((user) => user.id !== userId));
    onDeleteUser(allUsers.length - 1);
  };

  useEffect(() => {
    onChangeUsers?.(allUsers);
  }, [allUsers]);

  const columns = useMemo(
    () => [
      {
        accessorKey: 'email',
        header: 'Email пользователя',
        maxSize: 400,
        size: 200,
        Cell: ({ row }) => {
          const user = row.original;
          return <Typography>{user.email}</Typography>;
        },
        enableEditing: false,
        enableColumnActions: false,
      },
      {
        accessorKey: 'ssp',
        header: 'ССП/Региональный филиал',
        size: 134,
        maxSize: 268,
        Cell: ({ row }) => {
          return (
            <Autocomplete
              fullWidth
              size="small"
              options={sspOptions}
              getOptionLabel={(option) => option.title || option.name || ''}
              value={row.original.ssp}
              onChange={(e, newValue) =>
                handleSspChange(row.original.id, newValue || '')
              }
              sx={{
                height: '1.5rem',
                padding: 0,
                maxWidth: '10rem',

                '.MuiInputBase-root': {
                  height: '1.5rem',
                  border: '1px solid var(--stroke)',
                  borderRadius: '0.5rem',
                },
              }}
              renderInput={(params) => (
                <TextField
                  {...params}
                  placeholder="Не выбран"
                  size="small"
                  variant="outlined"
                  sx={{
                    fontSize: ' 0.88rem',
                    '.MuiInputBase-input': {
                      minWidth: '6.25rem',
                      padding: 0,
                    },
                  }}
                />
              )}
              freeSolo={false}
            />
          );
        },
        enableColumnActions: false,
      },
      {
        accessorKey: 'admin',
        header: 'Администратор',
        size: 70,
        maxSize: 140,
        Cell: ({ row }) => (
          <Box
            sx={StyleForChecked}
            onClick={() => handleRoleChange(row.original.id, 'admin')}
          >
            {row.original.admin ? (
              <CheckedIcon color="primary" />
            ) : (
              <CheckIcon />
            )}
          </Box>
        ),
        enableColumnActions: false,
      },
      {
        accessorKey: 'executor_dfip',
        header: 'Исполнитель ДФиП',
        size: 70,
        maxSize: 140,
        Cell: ({ row }) => (
          <Box
            sx={StyleForChecked}
            onClick={() => handleRoleChange(row.original.id, 'executor_dfip')}
          >
            {row.original.executor_dfip ? (
              <CheckedIcon color="success" />
            ) : (
              <CheckIcon />
            )}
          </Box>
        ),
        enableColumnActions: false,
      },
      {
        accessorKey: 'executor_rf',
        header: 'Исполнитель РФ',
        size: 70,
        maxSize: 140,
        Cell: ({ row }) => (
          <Box
            sx={StyleForChecked}
            onClick={() => handleRoleChange(row.original.id, 'executor_rf')}
          >
            {row.original.executor_rf ? (
              <CheckedIcon color="warning" />
            ) : (
              <CheckIcon />
            )}
          </Box>
        ),
        enableColumnActions: false,
      },
      {
        id: 'actions',
        header: '',
        size: 30,
        maxSize: 60,
        Cell: ({ row }) => {
          return (
            <Box
              sx={{
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
              }}
            >
              <IconButton
                size="small"
                onClick={() => handleDeleteUser(row.original.id)}
                sx={{ color: 'error.main' }}
              >
                <Box
                  display="flex"
                  sx={{
                    padding: '0.75rem 1.25rem',
                    width: '4rem',
                    height: '2.75rem',
                    justifyContent: 'center',
                    alignItems: 'center',
                  }}
                >
                  <TrashSvg fill={'red'} />
                </Box>
              </IconButton>
            </Box>
          );
        },
        enableEditing: false,
        enableSorting: false,
        enableColumnFilter: false,
        enableColumnActions: false,
        enableHiding: false,
      },
    ],
    [allUsers, sspOptions],
  );

  const table = useMaterialReactTable({
    columns,
    data: allUsers,
    enablePagination: false,
    enableBottomToolbar: false,
    enableDensityToggle: false,
    enableFullScreenToggle: false,
    enableRowActions: false,

    enableTopToolbar: false,

    enableColumnFilters: false,
    enableGlobalFilter: false,

    muiTableBodyRowProps: ({ _row }) => ({
      sx: {
        fontSize: '.75rem',
        height: '2.75rem',
        '& .MuiTableCell-root': {
          padding: 0,
          paddingLeft: '.5rem',
          height: '2.75rem',
          maxHeight: '2.75rem',
        },
      },
    }),
    muiTableHeadRowProps: {
      sx: {
        fontSize: (theme) => theme.adminTable.fontSize,
        height: (theme) =>
          theme.adminTable.MuiTableRow.styleOverrides.root.height,
        '& .MuiTableCell-root': {
          padding: 0,
          height: '2rem',
          textAlign: 'center',
          verticalAlign: 'middle',
          paddingLeft: '0.75rem',
        },
      },
    },
    muiTableBodyCellProps: {
      sx: {
        maxHeight: '2.75rem',
        fontSize: 'inherit',
      },
    },
    muiTableHeadCellProps: {
      sx: {
        fontSize: 'inherit',
        fontWeight: 'bold',
        backgroundColor: '#f5f5f5',
      },
    },
    muiTableProps: {
      sx: {
        '& thead': {
          position: 'sticky',
          top: 0,
          zIndex: 10,
        },
      },
    },
    muiTablePaperProps: {
      sx: {
        width: '72rem',
        maxWidth: '72rem',
        display: 'flex',
        flexDirection: 'column',
        minHeight: '18.38rem',
        boxShadow: 'none',
        border: 'none',
        background: 'transparent',
      },
    },
    muiTableContainerProps: {
      sx: {
        flex: '1 1 auto',
        overflow: 'auto',
        maxHeight: '18.38rem',
      },
    },
    enableRowNumbers: false,
    muiToolbarAlertBannerProps: false,
  });

  return (
    <Box
      sx={{
        display: 'flex',
        flexDirection: 'column',
        '& .MuiTableContainer-root': {
          overflow: 'auto',
        },
      }}
    >
      <MaterialReactTable table={table} />
    </Box>
  );
};

export default UserTableForAdd;
