'use client';

import React from 'react';
import Image from 'next/image';
import {
  Tooltip,
  TooltipContent,
  TooltipTrigger,
} from '@/components/ui/Tooltip';
import { MediaDetails } from '@/lib/fetch';
import { useAtom } from 'jotai';
import { selectedMediaIdAtom } from '@/state/media';
import { cn } from '@/lib/utils';

export interface MediaTileProps {
  media: MediaDetails;
}

export default function MediaTile({ media }: MediaTileProps) {
  const {
    url,
    thumbnails,
    id,
    name,
    properties: { width, height },
  } = media;
  const [selectedMediaId, setSelectedMediaId] = useAtom(selectedMediaIdAtom);
  const selected = selectedMediaId === id;
  // const imageSrc = thumbnails.length ? thumbnails[thumbnails.length - 1] : url;
  const imageSrc = url;
  return (
    <Tooltip>
      <TooltipTrigger asChild>
        <Image
          src={imageSrc}
          draggable={false}
          alt="dataset images"
          width={width}
          height={height}
          onClick={() => setSelectedMediaId(id)}
          className={cn(
            'w-full h-auto relative rounded-xl overflow-hidden shadow-md cursor-pointer transition-transform hover:scale-105 box-content',
            selected && 'border-2 border-primary',
          )}
        />
      </TooltipTrigger>
      <TooltipContent>
        <p>{name}</p>
        <p className="font-light text-xs">{`${width} x ${height}`}</p>
      </TooltipContent>
    </Tooltip>
  );
}
