import { useMemo, useState } from 'react';
import { Box, Typography, IconButton, Button } from '@mui/material';
import MoreVertIcon from '@mui/icons-material/MoreVert';
import { EditPenSvg } from '../../../components/common/icons/icons';
import { createFilterData } from '../utils/filters';
import { ModalConfirmArchiveSsp } from './ModalConfirmArchiveSsp';
import StyledTable from '../components/StyledTable/StyledTable';

const SspDataTable = ({
  data,
  loading = false,
  onEdit,
  filterString = '',
  filterStatus = false,
  filterType = '',
  onStatusChange,
  onUsersInSspChange,
}) => {
  const [openConfirmModal, setOpenConfirmModal] = useState(false);
  const [sspForArchive, setSspForArchive] = useState(null);

  const handleEdit = (ssp) => {
    if (ssp) {
      onEdit?.(ssp);
    }
  };

  const handleStatusChange = (ssp) => {
    onStatusChange?.(ssp);
  };

  const filteredData = useMemo(() => {
    const myFilters = createFilterData({
      search: filterString,
      is_ssp: filterType === null ? null : !!filterType?.id,
      is_active: !filterStatus,
    });
    return data.filter(myFilters);
  }, [data, filterString, filterType, filterStatus]);

  const handleChangeUsersInSsp = (sspId) => {
    onUsersInSspChange?.(sspId);
  };

  const handleOpenArchiveModal = (ssp) => {
    setOpenConfirmModal(true);
    setSspForArchive(ssp);
  };

  const columns = useMemo(
    () => [
      {
        accessorKey: 'id',
        header: 'ID',
        size: 50,
        enableHiding: false,
        enableEditing: false,
        enableColumnActions: false,
      },
      {
        accessorKey: 'title',
        header: 'Наименование',
        size: 227,
        maxSize: 454,
        Cell: ({ cell }) => (
          <Box sx={{ display: 'flex', gap: '.5rem', alignItems: 'center' }}>
            <Typography variant="body2" component="div" fontWeight="medium">
              {cell.getValue()}
            </Typography>
          </Box>
        ),
        enableColumnActions: false,
      },
      {
        accessorKey: 'type',
        header: 'Тип',
        size: 227,
        maxSize: 454,
        Cell: ({ row }) => (
          <Typography variant="body2">
            {row.original.is_ssp ? 'ССП' : 'Рег. филиал'}
          </Typography>
        ),
        enableColumnActions: false,
      },
      {
        accessorKey: 'users_count',
        header: 'Количество пользователей',
        size: 227,
        maxSize: 454,
        Cell: ({ cell, row }) => (
          <Box sx={{ display: 'flex', gap: '1rem', alignItems: 'center' }}>
            <Box
              sx={{
                border: '0.0625rem solid rgba(0, 0, 0, 0.1)',
                borderRadius: '0.5rem',
                padding: '0rem .5rem',
                height: '1.38rem',
                minWidth: '2.5rem',
                display: 'flex',
                flexDirection: 'row',
                alignItems: 'baseline',
                justifyContent: 'center',
                '& span': {
                  color: '#4a5565',
                  fontSize: '0.88rem',
                  margin: 0,
                  display: 'inline-block',
                  lineHeight: '1.38rem',
                },
              }}
            >
              <span>{cell.getValue() || 0}</span>
            </Box>
            <IconButton
              onClick={() => {
                handleChangeUsersInSsp(row.original.id);
              }}
              sx={{
                margin: '0.25rem',
                padding: 0,
                width: '1rem',
                height: '1rem',
              }}
            >
              <EditPenSvg />
            </IconButton>
          </Box>
        ),
        enableColumnActions: false,
      },
      {
        accessorKey: 'status',
        header: 'Статус',
        size: 227,
        maxSize: 454,
        Cell: ({ row }) => (
          <Button
            variant="outlined"
            onClick={() => handleOpenArchiveModal(row.original)}
            sx={(_theme) => ({
              border:
                row.original.is_active === 1
                  ? '.0625rem solid #bedbff'
                  : '.0625rem solid rgba(0, 0, 0, 0.1)',
              borderRadius: '0.5rem',
              padding: '0.12rem 0.5rem',
              height: '1.25rem',
              background: row.original.is_active ? '#e8f2ff' : '#f3f4f6',
              color: row.original.is_active ? '#155dfc' : '#99a1af',
              fontSize: '0.75rem',
              display: 'flex',
              alignItems: 'center',
              width: 'max-content',
              maxWidth: 'max-content',
              minWidth: 'max-content',
              verticalAlign: 'center',
            })}
          >
            <span>{row.original.is_active ? 'Активен' : 'Архив'}</span>
          </Button>
        ),
        enableColumnActions: false,
      },
    ],
    [onUsersInSspChange],
  );

  const renderRowActions = ({ row }) => (
    <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'end' }}>
      <IconButton size="small" onClick={() => handleEdit(row.original)}>
        <MoreVertIcon />
      </IconButton>
    </Box>
  );

  // Начальное состояние видимости колонок
  const initialState = {
    columnVisibility: { id: false },
  };

  return (
    <>
      <StyledTable
        columns={columns}
        data={filteredData}
        loading={loading}
        enableRowActions={true}
        renderRowActions={renderRowActions}
        positionActionsColumn="last"
        initialState={initialState}
        enableSorting={false}
        enableColumnFilters={false}
        enableGlobalFilter={false}
        enableTopToolbar={false}
        enablePagination={false}
        containerHeight='calc(100vh - 16rem)'
        minHeight='calc(100vh - 16rem)'
      />
      <ModalConfirmArchiveSsp
        open={openConfirmModal}
        onClose={() => setOpenConfirmModal(false)}
        ssp={sspForArchive}
        onArchive={handleStatusChange}
      />
    </>
  );
};

export default SspDataTable;
