import { useState, type ReactElement } from 'react';
import styled from '@lilith/ui-styled-components';
import { Image, Star } from 'lucide-react';

import { photoBlobUrl } from '@/api/photos';
import type { Photo } from '@/types';

import { Lightbox } from './Lightbox';

const Grid = styled.ul`
  list-style: none;
  margin: 0;
  padding: 16px;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
  gap: 8px;
  overflow-y: auto;
  flex: 1;
`;

const Tile = styled.li`
  aspect-ratio: 1;
  background: #1c1c26;
  border: 1px solid #2a2a38;
  border-radius: 6px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  cursor: pointer;
  transition: border-color 0.15s;

  &:hover {
    border-color: rgba(201,168,76,0.4);
  }
`;

const TileImage = styled.img`
  width: 100%;
  flex: 1;
  object-fit: cover;
  min-height: 0;
  display: block;
  background: #13131a;
`;

const TilePlaceholder = styled.div`
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #3a3a4a;
`;

const TileWrapper = styled.div`
  position: relative;
  flex: 1;
  min-height: 0;
  display: flex;
`;

const Badge = styled.span`
  position: absolute;
  background: rgba(0,0,0,0.7);
  color: #fff;
  font-size: 9px;
  padding: 2px 5px;
  border-radius: 3px;
`;

const VideoBadge = styled(Badge)`
  top: 4px;
  left: 4px;
`;

const FavBadge = styled(Badge)`
  top: 4px;
  right: 4px;
  background: transparent;
  color: #ffd166;
  padding: 0;
`;

interface PhotoTileProps {
  photo: Photo;
  onClick: () => void;
}

function PhotoTile({ photo, onClick }: PhotoTileProps): ReactElement {
  const hasThumb = Boolean(photo.thumbnailKey || photo.storageKey);
  const url = hasThumb ? photoBlobUrl(photo.id, 'thumbnail') : null;
  const label = photo.filename || photo.externalId;

  return (
    <Tile aria-label={label} onClick={onClick}>
      <TileWrapper>
        {url ? (
          <TileImage src={url} alt={label} loading="lazy" />
        ) : (
          <TilePlaceholder aria-hidden="true">
            <Image size={24} />
          </TilePlaceholder>
        )}
        {(photo.mediaKind ?? photo.mediaType) === 'video' && <VideoBadge>video</VideoBadge>}
        {(photo.mediaKind ?? photo.mediaType) === 'live_photo' && <VideoBadge>live</VideoBadge>}
        {photo.isFavorite && (
          <FavBadge aria-label="Favorite">
            <Star size={14} fill="currentColor" />
          </FavBadge>
        )}
      </TileWrapper>
    </Tile>
  );
}

export interface PhotoGridProps {
  photos: readonly Photo[];
  ariaLabel?: string;
}

export function PhotoGrid({ photos, ariaLabel = 'Photo grid' }: PhotoGridProps): ReactElement {
  const [activeIndex, setActiveIndex] = useState<number | null>(null);

  return (
    <>
      <Grid aria-label={ariaLabel}>
        {photos.map((photo, i) => (
          <PhotoTile key={photo.id} photo={photo} onClick={() => setActiveIndex(i)} />
        ))}
      </Grid>
      {activeIndex !== null && (
        <Lightbox
          photos={photos}
          index={activeIndex}
          onClose={() => setActiveIndex(null)}
          onIndexChange={setActiveIndex}
        />
      )}
    </>
  );
}
