import ChevronRight from '@mui/icons-material/ChevronRight'
import {
  Box,
  Button,
  Card as MuiCard,
  CardActions,
  CardContent,
  CardHeader,
  CardMedia,
  styled,
} from '@mui/material'
import { ReactNode } from 'react'

interface CardProps {
  title: string | ReactNode
  subheader?: string | ReactNode
  children?: ReactNode
  footer?: {
    buttonText?: string | ReactNode
    onClick: () => void
    endIcon?: ReactNode
    buttonProps?: any
  }
  image?: {
    url: string
    height: number
  }
  moreActions?: ReactNode
}

export default function Card({
  title,
  subheader,
  children,
  footer,
  image,
  moreActions,
}: CardProps) {
  const handleClick = (e) => {
    e.preventDefault()
    e.stopPropagation()
    footer?.onClick()
  }

  return (
    <StyledCard>
      <CardMedia component="img" height={image?.height} image={image?.url} />
      <Box sx={{ position: 'relative', width: '100%' }}>
        <StyledMoreActions>{moreActions}</StyledMoreActions>
        <CardHeader title={title} subheader={subheader} />
      </Box>
      <CardContent sx={{ height: 'fit-content' }}>{children}</CardContent>
      {footer && (
        <StyledCardActions>
          <Button
            variant="text"
            fullWidth
            onClick={handleClick}
            endIcon={footer?.endIcon ?? <ChevronRight />}
            {...footer?.buttonProps}
            sx={{ fontSize: '14px' }}
          >
            {footer?.buttonText ?? 'View'}
          </Button>
        </StyledCardActions>
      )}
    </StyledCard>
  )
}

const StyledMoreActions = styled(Box)(({ theme }) => ({
  position: 'absolute',
  right: '10px',
  top: '15px',
}))

const StyledCard = styled(MuiCard)(({ theme }) => ({
  display: 'flex',
  flexDirection: 'column',
  width: '100%',
  height: '100%',
  '& .MuiCardContent-root': {
    flexGrow: 1,
  },
  '& .MuiCardHeader-root': {
    alignItems: 'baseline',
    gap: '6px',
  },
}))

const StyledCardActions = styled(CardActions)(({ theme }) => ({
  borderTop: theme.borders.grayLight,
  '& .MuiButton-root': {
    justifyContent: 'space-between',
    height: '40px',
    padding: '20px',
  },
}))
