import { type FC } from 'react';

import CardMedia from '@material-hu/mui/CardMedia';
import { type SxProps, type Theme, useTheme } from '@material-hu/mui/styles';

import { CATEGORY_ICONS } from 'src/constants/serviceManagement';
import { type ServiceItem } from 'src/pages/dashboard/serviceManagement/types';

export type CoverPictureProps = {
  serviceItem?: ServiceItem;
  sx?: SxProps<Theme>;
};

const ASPECT_RATIO = 4.04;

const CoverPicture: FC<CoverPictureProps> = ({ serviceItem, sx }) => {
  const theme = useTheme();

  if (!serviceItem) return null;

  const IconComponent = serviceItem.category
    ? CATEGORY_ICONS[serviceItem.category.icon as keyof typeof CATEGORY_ICONS]
        ?.Icon
    : null;

  const hasCustomCoverPicture =
    serviceItem.coverPictureEnabled && serviceItem.coverPicture;
  const hasDefaultCoverPicture =
    serviceItem.coverPictureEnabled && !serviceItem.coverPicture;
  const hasCategoryCoverPicture =
    !serviceItem.coverPictureEnabled && serviceItem.category;

  if (hasCustomCoverPicture) {
    return (
      <CardMedia
        src={serviceItem.coverPicture?.url}
        component="img"
        loading="lazy"
        sx={{
          width: 1,
          aspectRatio: ASPECT_RATIO,
          objectFit: 'fill',
          ...sx,
        }}
      />
    );
  } else if (hasDefaultCoverPicture) {
    return (
      <CardMedia
        component="div"
        sx={{
          width: 1,
          aspectRatio: ASPECT_RATIO,
          backgroundImage: ({ palette }) =>
            `linear-gradient(to right, ${palette.newBase?.brand[300]}, ${palette.newBase?.brand[500]})`,
          ...sx,
        }}
      />
    );
  } else if (hasCategoryCoverPicture) {
    return (
      <CardMedia
        component="div"
        sx={{
          width: 1,
          aspectRatio: ASPECT_RATIO,
          backgroundColor: ({ palette }) => palette.new.border.neutral.default,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          ...sx,
        }}
      >
        {IconComponent && (
          <IconComponent
            size={24}
            style={{ color: theme.palette.new.text.neutral.default }}
          />
        )}
      </CardMedia>
    );
  }
  return (
    <CardMedia
      component={'div'}
      sx={{
        width: 1,
        aspectRatio: ASPECT_RATIO,
        backgroundColor: ({ palette }) => palette.new.border.neutral.default,
        ...sx,
      }}
    />
  );
};

export default CoverPicture;
