import { useState } from 'react';
import { useLocation, useNavigate } from 'react-router';

import Card from '@material-hu/mui/Card';
import CardActionArea from '@material-hu/mui/CardActionArea';
import CardContent from '@material-hu/mui/CardContent';
import CardMedia from '@material-hu/mui/CardMedia';
import Grid from '@material-hu/mui/Grid';
import { useTheme } from '@material-hu/mui/styles';
import Typography from '@material-hu/mui/Typography';

import Pills from '@material-hu/components/design-system/Pills';
import ProgressBar from '@material-hu/components/design-system/ProgressIndicators/ProgressBar';
import Title from '@material-hu/components/design-system/Title';

import defaultCourseImg from 'src/assets/svg/newDefaultCourse.svg';
import useFormatDate from 'src/hooks/useFormatDate';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { getDurationTime } from 'src/utils/time';

import useRoutes from '../../../hooks/useRoutes';
import { COURSE_IMG_ASPECT_RATIO } from '../../constants';
import { type CourseListItem } from '../../types';

export type CourseCardProps = {
  course: CourseListItem;
};

export const CourseCard = ({ course }: CourseCardProps) => {
  const [img, setImg] = useState(course.pictureUrl ?? defaultCourseImg);
  const { palette, shadows, shape, spacing } = useTheme();
  const { t } = useLokaliseTranslation('learning');
  const location = useLocation();
  const { formatDate } = useFormatDate();
  const navigate = useNavigate();
  const routes = useRoutes();

  const handleClick = () =>
    navigate(routes.courses.detail(course.id), {
      state: {
        fromList: true,
        backRoute: `${location.pathname}${location.search}`,
      },
    });

  const handleImgError = () => setImg(defaultCourseImg);

  const duration = getDurationTime(course.durationTime);

  const dueDate =
    course.dueDate &&
    t('common.due_date', { date: formatDate(course.dueDate) });

  const showDivider = duration && dueDate;
  const detailsEmpty = !duration && !dueDate;

  return (
    <Grid
      item
      xs
    >
      <Card
        elevation={0}
        sx={{
          position: 'relative',
          height: '100%',
          overflow: 'hidden',
          borderRadius: shape.borderRadiusL,
        }}
      >
        <CardActionArea
          onClick={handleClick}
          sx={{
            height: '100%',
            widht: '100%',
            display: 'flex',
            flexDirection: 'column',
            justifyContent: 'flex-start',
            borderRadius: shape.borderRadiusL,
            '& .MuiCardActionArea-focusHighlight': {
              display: 'none',
            },
            border: 'solid 1px',
            borderColor: palette.new.border.neutral.divider,
            '&:hover, :focus-visible': {
              border: 'solid 1px',
              borderColor: palette.new.border.neutral.default,
              boxShadow: shadows?.[1],
            },
          }}
        >
          <CardMedia
            component="img"
            src={img}
            alt=""
            onError={handleImgError}
            sx={{
              borderRadius: shape.borderRadiusL,
              borderBottomLeftRadius: 0,
              borderBottomRightRadius: 0,
              aspectRatio: COURSE_IMG_ASPECT_RATIO,
              objectFit: 'cover',
            }}
          />
          <Pills
            hasIcon={false}
            label={
              course.isObligatory ? t('course.required') : t('course.optional')
            }
            type={course.isObligatory ? 'highlight' : 'neutral'}
            sx={{
              position: 'absolute',
              top: spacing(2),
              right: spacing(2),
            }}
          />
          <CardContent
            sx={{
              width: '100%',
              display: 'flex',
              flexDirection: 'column',
              gap: 1.5,
              p: `${spacing(1.5)} !important`,
              backgroundColor: palette.new.background.elements.default,
            }}
          >
            <Title
              variant="M"
              title={course.title}
              copetin={course.category?.name?.toUpperCase()}
              overflow="tooltip"
              withEllipsis
              sx={{ pt: course.category ? 0 : 2 }}
            />
            <ProgressBar
              variant="determinate"
              current={course.progress}
              hasPercentage
            />
            <Typography
              variant="globalS"
              sx={{
                display: 'flex',
                flexDirection: 'row',
                gap: 1,
                color: palette.new.text.neutral.default,
              }}
            >
              {detailsEmpty && t('common.no_due_date')}
              {duration && <span>{duration}</span>}
              {showDivider && <span>{'•'}</span>}
              {dueDate && <span>{dueDate}</span>}
            </Typography>
          </CardContent>
        </CardActionArea>
      </Card>
    </Grid>
  );
};

export default CourseCard;
