import React, { FC } from 'react';
import styled from 'styled-components';

import {
  Button,
  Card,
  CardContent,
  CardMedia,
  Dialog,
  IconButton,
  Typography,
} from '@material-ui/core';
import { Close, ExitToApp } from '@material-ui/icons';

import { User } from './userSlice';

type UserProfileProps = {
  handleClose: (signOut?: boolean) => void;
  open: boolean;
} & User['profile'] &
  Pick<User['preferences'], 'roles'>;

const StyledCard = styled(Card)`
  display: flex;
  margin: auto;
  max-width: 345px;
`;
const Details = styled.div`
  display: flex;
  flex-direction: column;
`;
const Controls = styled.div`
  display: flex;
  align-items: center;
  padding-left: ${({ theme }) => theme.spacing(1)}px;
  padding-bottom: ${({ theme }) => theme.spacing(1)}px;
`;
const StyledCardContent = styled(CardContent)`
  flex: 1 0 auto;
`;
const StyledCardMedia = styled(CardMedia)`
  width: 151px;
`;
const StyledButton = styled(Button)`
  margin: auto;
`;
const StyledIconButton = styled(IconButton)`
  position: absolute;
  right: 3px;
  top: 0;
`;

const UserProfile: FC<UserProfileProps> = ({
  handleClose,
  open,
  image,
  name,
  email,
  roles = [],
}) => (
  <Dialog onClose={() => handleClose()} open={open}>
    {open && (
      <StyledCard>
        <Details>
          <StyledCardContent>
            <Typography component="h5" variant="h5">
              {name}
            </Typography>
            <Typography variant="subtitle1" color="textSecondary">
              {email}
            </Typography>
            <Typography variant="subtitle2" color="textSecondary">
              Roles: {roles.join(', ')}
            </Typography>
          </StyledCardContent>
          <Controls>
            <StyledButton
              startIcon={<ExitToApp />}
              onClick={() => handleClose(true)}
            >
              Log Out
            </StyledButton>
          </Controls>
        </Details>
        <StyledIconButton onClick={() => handleClose()} edge="end" size="small">
          <Close />
        </StyledIconButton>
        <StyledCardMedia
          image={image.replace(/-o=.*$/, '-o=s150')}
          title="Profile Picture"
        />
      </StyledCard>
    )}
  </Dialog>
);

export default UserProfile;
