import { CommentOutlined } from "@ant-design/icons";
import { Card, Flex, Typography } from "antd";
import { LessonPreview } from "core/types/lesson";
import { Constants, getImageUrl } from "core/utils/utils";
import { Link } from "react-router-dom";
import MyUpload from "shared/components/MyUpload";
import styles from "./styles.module.css";

export default function MyLessonPreviewCard({
  mode = "view",
  lessonId,
  loading = false,
  lessonPreview,
  onEditTitle,
  onThumbnailChanged,
}: {
  mode: "view" | "editable";
  lessonId: string;
  loading?: boolean;
  lessonPreview: LessonPreview;
  onEditTitle?: (newTitle: string) => void;
  onThumbnailChanged?: () => void;
}) {
  const LinkWrapper = ({ children }: { children: React.ReactNode }) => {
    if (mode === "editable") return <>{children}</>;

    return (
      <Link
        to={Constants.ROUTE_PATHS.LESSIONS.PAGE.replace(":lessonId", lessonId)}
      >
        {children}
      </Link>
    );
  };

  const UploadWrapper = ({ children }: { children: React.ReactNode }) => {
    if (mode === "view") return <>{children}</>;

    return (
      <MyUpload
        action={`/lessons/${lessonId}/preview/thumbnail`}
        onChange={(info) => {
          if (info.file.status === "done") {
            onThumbnailChanged?.();
          }
        }}
        imgCropProps={{
          aspect: 5 / 4,
          children: <></>,
        }}
      >
        {children}
      </MyUpload>
    );
  };

  return (
    <LinkWrapper>
      <Card loading={loading}>
        <div className={styles.card}>
          <UploadWrapper>
            <img
              src={
                lessonPreview.ThumbnailUrl === ""
                  ? `${Constants.STATIC_CONTENT_ADDRESS}/demo/lesson_thumbnail.webp`
                  : getImageUrl(lessonPreview.ThumbnailUrl)
              }
              alt="lesson thumbnail"
              className={styles.img}
            />
          </UploadWrapper>

          <Flex vertical justify="center" style={{ width: "100%" }}>
            {mode === "view" ? (
              <div>
                <div className={styles.title}>{lessonPreview.Title}</div>
                <CommentOutlined /> 12 comments
              </div>
            ) : (
              <Typography.Title
                level={2}
                editable={{
                  triggerType: "text" as any,
                  tooltip: "click to edit text",
                  onChange: (event) => onEditTitle?.(event),
                }}
                style={{
                  width: "100%",
                }}
              >
                {lessonPreview.Title}
              </Typography.Title>
            )}
          </Flex>
        </div>
      </Card>
    </LinkWrapper>
  );
}
