import * as dataFormat from 'pages/CRUD/Users/table/UsersDataFormatters';

import React from 'react';
import { Link, useNavigate } from 'react-router-dom';

import { makeStyles } from 'styles/mui';
import { DataGrid } from '@mui/x-data-grid';

import MenuItem from '@mui/material/MenuItem';

import Button from '@mui/material/Button';
import Box from '@mui/material/Box';
import InputLabel from '@mui/material/InputLabel';
import FormControl from '@mui/material/FormControl';
import Select from '@mui/material/Select';
import TextField from '@mui/material/TextField';
import Grid from '@mui/material/Grid';
import CloseIcon from '@mui/icons-material/Close';
import Stack from '@mui/material/Stack';
import LinearProgress from '@mui/material/LinearProgress';

import Widget from 'components/Widget';
import Actions from '../../../../components/Table/Actions';
import Dialog from '../../../../components/Dialog';
import {
  actions,
  useManagementDispatch,
  useManagementState,
} from '../../../../context/ManagementContext';

const useStyles = makeStyles({
  container: {
    paddingTop: 10,
    paddingBottom: 10
  },
  actions: {
    display: 'flex',
    justifyContent: 'space-between',
    marginBottom: 10,
    '& a': {
      textDecoration: 'none',
      color: '#fff'
    }
  }
});

const UsersTable = () => {
  const managementDispatch = useManagementDispatch();
  const managementState = useManagementState();
  const navigate = useNavigate();
  const classes = useStyles();
  // eslint-disable-next-line no-unused-vars
  const [width, setWidth] = React.useState(window.innerWidth);

  const [filters] = React.useState([
  { label: 'First Name', title: 'firstName' },
  { label: 'Last Name', title: 'lastName' },
  { label: 'Phone Number', title: 'phoneNumber' },
  { label: 'E-Mail', title: 'email' }]
  );

  const [filterItems, setFilterItems] = React.useState([]);
  const [filterUrl, setFilterUrl] = React.useState('');
  const filterItemIdRef = React.useRef(0);

  const [loading, setLoading] = React.useState(false);
  const [sortModel, setSortModel] = React.useState([]);
  const [selectionModel, setSelectionModel] = React.useState([]);
  const count = managementState.count || 0;
  const modalOpen = managementState.modalOpen;
  const rows = managementState.rows;
  const idToDelete = managementState.idToDelete;

  const [rowsState, setRowsState] = React.useState({
    page: 0,
    pageSize: 5
  });

  const loadData = async (limit, page, orderBy, request) => {
    setLoading(true);
    await actions.doFetch({ limit, page, orderBy, request })(managementDispatch);
    setLoading(false);
  };

  React.useEffect(() => {
    loadData(rowsState.pageSize, rowsState.page, sortModel[0], filterUrl);
  }, [sortModel, rowsState, filterUrl]);

  React.useEffect(() => {
    updateWindowDimensions();
    window.addEventListener('resize', updateWindowDimensions);
    return () => window.removeEventListener('resize', updateWindowDimensions);
  }, []);

  const handleSortModelChange = (newModel) => {
    setSortModel(newModel);
  };

  const updateWindowDimensions = () => {
    setWidth(window.innerWidth);
  };

  const handleChange = (id) => (e) => {
    const value = e.target.value;
    const name = e.target.name;

    setFilterItems(
      filterItems.map((item) =>
      item.id === id ?
      { id, fields: { ...item.fields, [name]: value } } :
      item
      )
    );
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    let request = '&';
      filterItems.forEach((item) => {
      Object.hasOwn(
      filters[
      filters.map((filter) => filter.title).indexOf(item.fields.selectedField)],
      'number') ?
      request += `${item.fields.selectedField}Range=${item.fields.filterValueFrom}&${item.fields.selectedField}Range=${item.fields.filterValueTo}&` :
      request += `${item.fields.selectedField}=${item.fields.filterValue}&`;
    });

    loadData(rowsState.pageSize, 0, sortModel[0], request);
    setFilterUrl(request);
  };

  const handleReset = () => {
    setFilterItems([]);
    setFilterUrl('');
    actions.doFetch({ limit: rowsState.pageSize, page: 0, request: '' })(
      managementDispatch,
    );
  };

  const addFilter = () => {
    filterItemIdRef.current += 1;
    let newItem = {
      id: `filter_${filterItemIdRef.current}`,
      fields: {
        filterValue: '',
        filterValueFrom: '',
        filterValueTo: ''
      }
    };
    newItem.fields.selectedField = filters[0].title;
    setFilterItems([...filterItems, newItem]);
  };

  const deleteFilter = (value) => (e) => {
    e.preventDefault();
    const newItems = filterItems.filter((item) => item.id !== value);
    if (newItems.length) {
      setFilterItems(newItems);
    } else {
      actions.doFetch({ limit: 10, page: 1 })(managementDispatch);
      setFilterItems(newItems);
    }
  };

  const handleDelete = () => {
    actions.doDelete(
      { limit: 10, page: 0, request: filterUrl },
      idToDelete,
    )(managementDispatch);
  };

  const openModal = (event, cell) => {
    const id = cell;
    event.stopPropagation();
    actions.doOpenConfirm(id)(managementDispatch);
  };

  const closeModal = () => {
    actions.doCloseConfirm()(managementDispatch);
  };

  function NoRowsOverlay() {
    return (
      <Stack height='100%' alignItems='center' justifyContent='center'>
        No results found
      </Stack>);

  }

  const columns = [
  {
    field: 'firstName',

    flex: 0.6,

    headerName: 'First Name'
  },

  {
    field: 'lastName',

    flex: 0.6,

    headerName: 'Last Name'
  },

  {
    field: 'phoneNumber',

    flex: 0.6,

    headerName: 'Phone Number'
  },

  {
    field: 'email',

    flex: 0.6,

    headerName: 'E-Mail'
  },

  {
    field: 'role',

    headerName: 'Role'
  },

  {
    field: 'disabled',

    renderCell: (params) => dataFormat.booleanFormatter(params.row),

    headerName: 'Disabled'
  },

  {
    field: 'avatar',

    sortable: false,
    renderCell: (params) => dataFormat.imageFormatter(params.row),

    headerName: 'Avatar'
  },

  {
    field: 'id',
    headerName: 'Actions',
    sortable: false,
    flex: 0.6,
    maxWidth: 80,
    renderCell: (params) =>
    <Actions
      classes={classes}
      entity='users'
      openModal={openModal}
      {...params} />


  }];


  return (
    <div>
      <Widget title='Users' disableWidgetMenu>
        <Box className={classes.actions}>
          <Link to='/app/user/new'>
            <Button variant='contained'>New</Button>
          </Link>
          <Button type='button' variant='contained' onClick={addFilter}>
            Add Filter
          </Button>
        </Box>

        <Box sx={{ flexGrow: 1 }}>
          {filterItems.map((item) =>
          <Grid
            container
            alignItems='center'
            columns={12}
            spacing={1}
            className={classes.container}>
            
              <Grid size={3}>
                <FormControl size='small' fullWidth>
                  <InputLabel>Field</InputLabel>
                  <Select
                  label='Field'
                  name='selectedField'
                  size='small'
                  value={item.fields.selectedField}
                  onChange={handleChange(item.id)}>
                  
                    {filters.map((selectOption) =>
                  <MenuItem
                    key={selectOption.title}
                    value={`${selectOption.title}`}>
                    
                        {selectOption.label}
                      </MenuItem>
                  )}
                  </Select>
                </FormControl>
              </Grid>
              {Object.hasOwn(
            filters.find((filter) => filter.title === item.fields.selectedField) || {},
            'number',
          ) ?
            <>
                  <Grid size={2}>
                    <TextField
                  label='From'
                  type='text'
                  name='filterValueFrom'
                  size='small'
                  fullWidth
                  onChange={handleChange(item.id)} />
                
                  </Grid>
                  <Grid size={2}>
                    <TextField
                  label='To'
                  type='text'
                  name='filterValueTo'
                  size='small'
                  fullWidth
                  onChange={handleChange(item.id)} />
                
                  </Grid>
                </> :

            <Grid size={4}>
                  <TextField
                label='Contained'
                type='text'
                name='filterValue'
                size='small'
                fullWidth
                onChange={handleChange(item.id)} />
              
                </Grid>
            }

              <Grid size={2}>
                <Button
                variant='outlined'
                color='error'
                onClick={deleteFilter(item.id)}>
                
                  <CloseIcon />
                </Button>
              </Grid>
            </Grid>
          )}
          {filterItems.length > 0 &&
          <Grid container spacing={1}>
              <Grid>
                <Button variant='outlined' onClick={(e) => handleSubmit(e)}>
                  Apply
                </Button>
              </Grid>
              <Grid>
                <Button color='error' variant='outlined' onClick={handleReset}>
                  Clear
                </Button>
              </Grid>
            </Grid>
          }
        </Box>

        <div
          style={{
            minHeight: 500,
            width: '100%',
            paddingTop: 20,
            paddingBottom: 20
          }}>
          
          <DataGrid
            rows={loading ? [] : rows}
            rowCount={count}
            columns={columns}
            sortingMode='server'
            sortModel={sortModel}
            onSortModelChange={handleSortModelChange}
            rowsPerPageOptions={[5, 10, 20, 50, 100]}
            pageSize={5}
            pagination
            {...rowsState}
            paginationMode='server'
            components={{ NoRowsOverlay, LoadingOverlay: LinearProgress }}
            onPageChange={(page) => {
              setRowsState((prev) => ({ ...prev, page }));
            }}
            onPageSizeChange={(pageSize) => {
              setRowsState((prev) => ({ ...prev, pageSize }));
            }}
            onSelectionModelChange={(newSelectionModel) => {
              setSelectionModel(newSelectionModel);
            }}
            selectionModel={selectionModel}
            checkboxSelection
            disableSelectionOnClick
            disableColumnMenu
            loading={loading}
            onRowClick={(e) => {
              navigate(`/app/users/${e.id}/edit`);
            }}
            autoHeight />
          
        </div>
      </Widget>

      <Dialog
        open={modalOpen || false}
        title='Confirm delete'
        contentText='Are you sure you want to delete this item?'
        onClose={closeModal}
        onSubmit={handleDelete} />
      
    </div>);

};

export default UsersTable;
