import DownloadRoundedIcon from '@mui/icons-material/DownloadRounded';
import { IconButton, ImageList, ImageListItem } from '@mui/material';
import { useAppStyles } from '../styles/appStyles';
import type { PhotoItem } from '../types/data';
import { TiltCard } from './photography/TiltCard';

type QuiltedImageListProps = {
  imageData: PhotoItem[];
  albumLabel?: string;
  onPhotoClick?: (index: number) => void;
};

function srcset(image: string, size: number, rows = 1, cols = 1) {
  const correctPath = image.startsWith('./') ? image.substring(1) : image;
  return {
    src: `${correctPath}?w=${size * cols}&h=${size * rows}&fit=crop&auto=format`,
    srcSet: `${correctPath}?w=${size * cols}&h=${size * rows}&fit=crop&auto=format&dpr=2 2x`,
  };
}

function getDownloadFilename(image: string) {
  const sanitizedPath = image.split('?')[0].split('#')[0];
  const segments = sanitizedPath.split('/');
  return decodeURIComponent(segments[segments.length - 1] || 'photo');
}

export function QuiltedImageList({ imageData, albumLabel, onPhotoClick }: QuiltedImageListProps) {
  const appStyles = useAppStyles();

  return (
    <ImageList
      variant="quilted"
      cols={4}
      rowHeight={200}
      aria-label={albumLabel ? `${albumLabel} photo gallery` : undefined}
    >
      {imageData.map((item, index) => {
        const normalizedTitle = item.title.trim();
        const hasMeaningfulTitle =
          normalizedTitle.length > 0 && normalizedTitle.toLowerCase() !== 'missing';
        const altText = hasMeaningfulTitle
          ? normalizedTitle
          : `${albumLabel ?? 'Photo'} ${index + 1}`;

        return (
          <ImageListItem
            key={item.img}
            cols={item.cols || 1}
            rows={item.rows || 1}
            sx={appStyles.quiltedImageItemSx}
          >
            <TiltCard intensity={0.5} style={{ height: '100%', width: '100%' }}>
              <img
                {...srcset(item.img, 121, item.rows, item.cols)}
                alt={altText}
                loading="lazy"
                decoding="async"
                onClick={onPhotoClick ? () => onPhotoClick(index) : undefined}
                role={onPhotoClick ? 'button' : undefined}
                tabIndex={onPhotoClick ? 0 : undefined}
                onKeyDown={
                  onPhotoClick
                    ? (e) => {
                        if (e.key === 'Enter' || e.key === ' ') {
                          e.preventDefault();
                          onPhotoClick(index);
                        }
                      }
                    : undefined
                }
                style={onPhotoClick ? { cursor: 'pointer' } : undefined}
              />
              <IconButton
                className="photo-download-action"
                component="a"
                href={item.img}
                download={getDownloadFilename(item.img)}
                aria-label={`Download ${altText}`}
                size="small"
                sx={appStyles.photoDownloadButtonSx}
              >
                <DownloadRoundedIcon fontSize="small" />
              </IconButton>
            </TiltCard>
          </ImageListItem>
        );
      })}
    </ImageList>
  );
}
