import { type ReactElement } from 'react';
import styled from '@lilith/ui-styled-components';
import { Image } from 'lucide-react';
import { usePhotos } from '@/hooks/usePhotos';
import { EmptyState } from '@/components/EmptyState';
import { PageError } from '@/components/PageError';
import type { Photo } from '@/types';

const Root = styled.div`
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
`;

const PageHeading = styled.h1`
  margin: 0;
  padding: 14px 20px;
  font-size: 18px;
  font-weight: 700;
  color: #e0e0f0;
  border-bottom: 1px solid #2a2a38;
  background: #0a0a0f;
`;

const Meta = styled.span`
  font-size: 11px;
  color: #8a8a9a;
  padding: 8px 20px 4px;
`;

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: default;
  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 TileLabel = styled.span`
  font-size: 10px;
  color: #8a8a9a;
  padding: 4px 6px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
`;

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

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

const SpinnerWrap = styled.div`
  padding: 20px;
  font-size: 12px;
  color: #8a8a9a;
  text-align: center;
`;

function buildPhotoUrl(photo: Photo): string | null {
  if (!photo.storageKey) return null;
  return `/my/photos/${encodeURIComponent(photo.storageKey)}`;
}

function PhotoTile({ photo }: { photo: Photo }): ReactElement {
  const url = buildPhotoUrl(photo);
  const label = photo.filename || photo.externalId;

  return (
    <Tile aria-label={label}>
      <TileWrapper>
        {url ? (
          <TileImage src={url} alt={label} loading="lazy" />
        ) : (
          <TilePlaceholder aria-hidden="true">
            <Image size={24} />
          </TilePlaceholder>
        )}
        {photo.mediaType === 'video' && <VideoBadge aria-label="Video">video</VideoBadge>}
        {photo.mediaType === 'live_photo' && <VideoBadge aria-label="Live photo">live</VideoBadge>}
      </TileWrapper>
      <TileLabel title={label}>{label}</TileLabel>
    </Tile>
  );
}

export function PhotosTab(): ReactElement {
  const { data, isLoading, error } = usePhotos();

  return (
    <Root>
      <PageHeading>Photos</PageHeading>
      {isLoading && <SpinnerWrap aria-live="polite">Loading photos…</SpinnerWrap>}
      {error && <PageError message="Failed to load photos" />}
      {!isLoading && !error && data?.length === 0 && (
        <EmptyState icon={<Image size={36} />} heading="No photos" sub="Photos will appear here once sync runs." />
      )}
      {!isLoading && !error && data && data.length > 0 && (
        <>
          <Meta>{data.length} photo{data.length !== 1 ? 's' : ''}</Meta>
          <Grid aria-label="Photo grid">
            {data.map((photo) => (
              <PhotoTile key={photo.id} photo={photo} />
            ))}
          </Grid>
        </>
      )}
    </Root>
  );
}
