import Container from "@/components/Container/Container";
import Section from "@/components/Section/Section";
import GridItem from "@/components/GridItem/GridItem";
import { getCachedMediaByIds } from "@/services/wp";
import type { ReactElement } from "react";

export type MediaItem = {
  sourceUrl: string;
  alt: string;
  rowSpan: number;
  colSpan: number;
  mediaType: "image" | "video";
  videoUrl?: string;
  posterUrl?: string;
};

/** @deprecated Use MediaItem - kept for backward compatibility */
export type Image = MediaItem;

const MasonryImageGrid = async (props: { [key: string]: any }) => {
  const media: Array<{
    image: number | undefined;
    video: number | undefined;
    rowSpan: number;
    colSpan: number;
    mediaType: "image" | "video";
  }> = [];

  for (let i = 0; i < props.images; i++) {
    const imageKey = `images_${i}_image`;
    const rowKey = `images_${i}_row_span`;
    const colKey = `images_${i}_column_span`;
    const mediaTypeKey = `images_${i}_media_type`;
    const videoKey = `images_${i}_video`;

    const mediaType = (props[mediaTypeKey] as string) === "video" ? "video" : "image";
    const imageId = props[imageKey] != null ? Number(props[imageKey]) : undefined;
    const videoId = props[videoKey] != null ? Number(props[videoKey]) : undefined;

    media.push({
      image: imageId,
      video: mediaType === "video" ? videoId : undefined,
      rowSpan: Number(props[rowKey]) || 1,
      colSpan: Number(props[colKey]) || 1,
      mediaType,
    });
  }

  const payload: number[] = [];
  media.forEach((m) => {
    if (m.image != null) payload.push(m.image);
    if (m.video != null) payload.push(m.video);
  });
  const uniquePayload = Array.from(new Set(payload));

  const response =
    uniquePayload.length > 0
      ? await getCachedMediaByIds(uniquePayload)
      : [];
  const mediaById = new Map(response.map((item: any) => [item.id, item]));
  const composedMedia: MediaItem[] = [];

  media.forEach((m) => {
    const img = m.image != null ? mediaById.get(m.image) : undefined;
    const vid = m.video != null ? mediaById.get(m.video) : undefined;

    const sourceUrl = img?.source_url ?? "";
    const posterUrl = img?.source_url;
    const videoUrl = vid?.source_url;
    const alt = img?.alt_text ?? img?.alt ?? vid?.alt_text ?? vid?.alt ?? "";

    composedMedia.push({
      sourceUrl,
      alt,
      rowSpan: m.rowSpan,
      colSpan: m.colSpan,
      mediaType: m.mediaType,
      ...(m.mediaType === "video" && videoUrl && { videoUrl }),
      ...(posterUrl && { posterUrl }),
    });
  });

  return (
    <Container id={props.anchor}>
      <Section gridArea="wide" className="lg:px-md">
        {props.title && <h3 className="h1 text-center mb-md">{props.title}</h3>}
        <PureMasonryImageGrid media={composedMedia} />
      </Section>
    </Container>
  );
};

export const PureMasonryImageGrid = ({
  media,
  renderGridImageProp = null,
}: {
  media: MediaItem[];
  renderGridImageProp?: ((index: number, item: MediaItem) => React.ReactNode) | null;
}): ReactElement<any> => (
  <div className="grid grid-cols-2 md:grid-cols-3 auto-rows-auto grid-flow-row-dense gap-xs lg:gap-sm">
    {media.map((item, index) =>
      renderGridImageProp
        ? renderGridImageProp(index, item)
        : <GridItem key={index} item={item} index={index} />,
    )}
  </div>
);

export default MasonryImageGrid;
