import { type ReactElement } from 'react';
import styled from '@lilith/ui-styled-components';
import { FolderOpen } from 'lucide-react';

import { photoBlobUrl } from '@/api/photos';
import { EmptyState } from '@/components/EmptyState';
import { PageError } from '@/components/PageError';
import { useAlbums } from '@/hooks/usePhotos';
import type { Album } from '@/types';

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

const Tile = styled.li`
  background: #1c1c26;
  border: 1px solid #2a2a38;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  transition: border-color 0.15s;

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

const Cover = styled.div`
  aspect-ratio: 1;
  background: #13131a;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #3a3a4a;
`;

const CoverImage = styled.img`
  width: 100%;
  height: 100%;
  object-fit: cover;
`;

const Info = styled.div`
  padding: 8px 10px;
`;

const Name = styled.div`
  font-size: 13px;
  color: #e0e0f0;
  font-weight: 600;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
`;

const Count = styled.div`
  font-size: 10px;
  color: #8a8a9a;
  margin-top: 2px;
`;

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

export interface AlbumsViewProps {
  deviceId: string | undefined;
  onAlbumClick: (album: Album) => void;
}

export function AlbumsView({ deviceId, onAlbumClick }: AlbumsViewProps): ReactElement {
  const { data, isLoading, error } = useAlbums(deviceId);

  if (!deviceId) {
    return <EmptyState icon={<FolderOpen size={36} />} heading="No device selected" sub="Select a device to view albums." />;
  }
  if (isLoading) return <SpinnerWrap aria-live="polite">Loading albums…</SpinnerWrap>;
  if (error) return <PageError message="Failed to load albums" />;
  if (!data || data.length === 0) {
    return <EmptyState icon={<FolderOpen size={36} />} heading="No albums" sub="Albums will appear here once sync runs." />;
  }

  return (
    <Grid aria-label="Album grid">
      {data.map((album) => (
        <Tile key={album.id} onClick={() => onAlbumClick(album)}>
          <Cover>
            {album.coverPhotoId ? (
              <CoverImage src={photoBlobUrl(album.coverPhotoId, 'thumbnail')} alt={album.name} loading="lazy" />
            ) : (
              <FolderOpen size={32} />
            )}
          </Cover>
          <Info>
            <Name title={album.name}>{album.name}</Name>
            <Count>
              {album.photoCount} photo{album.photoCount === 1 ? '' : 's'} · {album.albumType}
            </Count>
          </Info>
        </Tile>
      ))}
    </Grid>
  );
}
