import { Media } from '@/payload-types'
import { GalleryItem } from '@/components/Gallery/Gallery'
import { StaticImageData } from 'next/image'

type Items = {
  photo: string | Media;
  caption?: string | null;
  id?: string | null;
}[];

export const transformGallery = (items: Items) => {
  const galleryItems: GalleryItem[] = []

  items.forEach(item => {
    if (typeof item === "object" && typeof item.photo === "object" && item.id) {
      const thumbnail = getPhoto("gallery", item.photo);
      const image = getPhoto("tablet", item.photo);

      if (thumbnail && image) {
        galleryItems.push({
          alt: item.photo.alt,
          id: item.id,
          thumbnail,
          image,
          caption: item.caption ?? undefined
        })
      }
    }
  })

  return galleryItems
}

type Size = "thumbnail" | "banner" | "gallery" | "tablet";
type OptionalMedia = string | null | undefined | Media;

/**
 * Get image data from optional media
 *
 */
export const getPhoto = (size: Size, data: OptionalMedia): StaticImageData | undefined => {
  if (!data) {
    return undefined;
  }

  if (typeof data === "string") {
    return undefined;
  }

  if (!data.sizes) {
    return undefined;
  }

  const sizeData = data.sizes[size]

  if (!sizeData) {
    // return original
    if (data.url && data.width && data.height)
      return {
        src: data.url,
        width: data.width,
        height: data.height
      };

    return undefined;
  }

  if (sizeData.url && sizeData.width && sizeData.height) {
    return {
      src: sizeData.url,
      width: sizeData.width,
      height: sizeData.height
    }
  }

  // return original
  if (data.url && data.width && data.height)
    return {
      src: data.url,
      width: data.width,
      height: data.height
    };

  return undefined;
}

