import React from 'react';
import { Table, TableBody, TableRow, TableCell, Paper, TableHead, Fab } from '@material-ui/core';
import AddIcon from '@material-ui/icons/Add';
import { entityProperties } from '../../data/appData';
import styleConstants from '../../styleConstants';

export default ({ entities, entityId, history }) => {
    const entityData = entityProperties(entityId);

    return (
        <Paper>
            <Table>
                <TableHead>
                    <TableRow>
                        <TableCell>
                            <span>{entityId}</span>
                            <div css={{ position: 'relative' }}>
                                <Fab
                                    onClick={() =>
                                        history.push(`/${entityId}/new`, {
                                            entities: entities
                                        })
                                    }
                                    css={{ position: 'absolute', left: 132, top: -50, zIndex: 10 }}
                                    color="primary"
                                    aria-label="Add"
                                    >
                                    <AddIcon />
                                </Fab>
                            </div>
                        </TableCell>
                    </TableRow>
                </TableHead>
                <TableBody
                    css={{
                        '&:hover': {
                            cursor: 'pointer'
                        }
                    }}>
                    {entities.map((d) => (
                        <TableRow
                            onClick={() =>
                                history.push(`/${entityId}/${d.id}`, {
                                    entities: entities
                                })
                            }
                            css={{
                                backgroundColor:
                                    history.location.pathname.split('/')[2] === d.id.toString()
                                        ? styleConstants.mainColorPalette[100]
                                        : 'inherit',
                                '&:hover': {
                                    backgroundColor: '#f0f0f0'
                                }
                            }}
                            key={d.id}>
                            {Object.keys(entityData.schema)
                                .filter((p) => entityData.primaryFields.includes(p))
                                .map((p) => (
                                    <TableCell key={p}>{d[p]}</TableCell>
                                ))}
                        </TableRow>
                    ))}
                </TableBody>
            </Table>
        </Paper>
    );
};
