import { Avatar, Card, CardContent, CardHeader, Link as MUILink, Typography } from '@mui/material';
import { Link } from '@tanstack/react-router';
import { FC } from 'react';
import Api from '../../api/Api';
import { PostAuth, PostNonAuth } from '../../types/Post';
import convertDate from '../../utils/date';

interface Props {
  post: PostNonAuth | PostAuth;
}

const Post: FC<Props> = ({ post }) => {
  return (
    <Card sx={{ display: 'flex', flexDirection: 'column', flexGrow: 1 }}>
      <CardHeader
        avatar={
          'id' in post.user ? (
            <MUILink
              component={Link}
              to="/profile/$id"
              params={{ id: post.user.id }}
              color="#FFF"
              variant="h6"
              underline="none"
            >
              <Avatar alt={post.user.username} src={`storage/${post.user.image}`} />
            </MUILink>
          ) : (
            <Avatar alt={post.user.username} src={`storage/${post.user.image}`} />
          )
        }
        title={
          'id' in post.user ? (
            post.user.id !== Api.getAuthenticatedUser()?.id ? (
              <MUILink component={Link} to="/profile/$id" params={{ id: post.user.id }}>
                {post.user.username}
              </MUILink>
            ) : (
              <MUILink component={Link} to="/profile">
                {post.user.username}
              </MUILink>
            )
          ) : (
            post.user.username
          )
        }
        subheader={convertDate(post.postedAt)}
      />
      <CardContent>
        <Typography>{post.content}</Typography>
      </CardContent>
    </Card>
  );
};

export default Post;
