import * as React from 'react';
import { marked } from 'marked';
import { Box, Typography, Divider, IconButton, Chip } from '@mui/material';
import { styled } from '@mui/material/styles';
import ArrowBackRoundedIcon from '@mui/icons-material/ArrowBackRounded';
import EditRoundedIcon from '@mui/icons-material/EditRounded';
import { ArticleMeta } from "../ArticleMeta";
import { ArticleViewProps } from '../../types/props';
import {useAuth} from "../../providers/Author";

const ArticleContainer = styled(Box)(({ theme }) => ({
  maxWidth: '800px',
  margin: '0 auto',
  padding: theme.spacing(4),
  [theme.breakpoints.down('sm')]: {
    padding: theme.spacing(2),
  },
}));

const CoverImage = styled('img')({
  width: '100%',
  height: 'auto',
  borderRadius: '12px',
  marginTop: '16px',
  marginBottom: '24px',
});

export default function ArticleView({
  article,
  onBack,
  onEdit,
}: ArticleViewProps) {

  const { currentUser } = useAuth();

  return (
    <ArticleContainer>
    <Box
      sx={{
        display: "flex",
        justifyContent: "space-between",
        mb: 2,
      }}
    >
      <IconButton onClick={onBack}>
        <ArrowBackRoundedIcon />
      </IconButton>

      {currentUser && (
        <IconButton onClick={onEdit}>
          <EditRoundedIcon />
        </IconButton>
      )}
    </Box>

      <Typography variant="h3" component="h1" gutterBottom fontWeight="bold">
        {article.title}
      </Typography>

      <ArticleMeta article={article} />

      <Divider sx={{ my: 3 }} />

      <Chip
        label={article.tag}
        variant="outlined"
        color="primary"
        sx={{ mb: 2, textTransform: 'uppercase', fontWeight: 500 }}
      />

      <CoverImage
        src={(
          import.meta.env.VITE_API_BASE_URL.replace(/\/+$/, "") +
          "/" +
          (article.img?.replace(/^\/+/, "") || "")
        )}
        alt={article.title}
      />

      <Box
        sx={{
          '& h3': { fontWeight: 600, mt: 4 },
          '& p': { color: 'text.primary', lineHeight: 1.8, mt: 2 },
          '& em': { fontStyle: 'italic' },
          '& ul': { pl: 3 },
        }}
        dangerouslySetInnerHTML={{ __html: marked(article.content) }}
      />
    </ArticleContainer>
  );
}
