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

import { EmptyState } from '@/components/EmptyState';
import { PageError } from '@/components/PageError';
import { usePhotos } from '@/hooks/usePhotos';
import type { Album, Photo } from '@/types';

import { AlbumDetail } from './AlbumDetail';
import { AlbumsView } from './AlbumsView';
import { IdentitiesView } from './IdentitiesView';
import { PhotoGrid } from './PhotoGrid';

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

const PageHeading = styled.div`
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 14px 20px;
  border-bottom: 1px solid #2a2a38;
  background: #0a0a0f;
`;

const Title = styled.h1`
  margin: 0;
  font-size: 18px;
  font-weight: 700;
  color: #e0e0f0;
`;

const Tabs = styled.div`
  display: flex;
  gap: 4px;
`;

const TabButton = styled.button<{ $active: boolean }>`
  background: ${(p) => (p.$active ? '#1c1c26' : 'transparent')};
  color: ${(p) => (p.$active ? '#e0e0f0' : '#8a8a9a')};
  border: 1px solid ${(p) => (p.$active ? 'rgba(201,168,76,0.4)' : '#2a2a38')};
  border-radius: 4px;
  padding: 4px 10px;
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  cursor: pointer;

  &:hover {
    color: #e0e0f0;
  }
`;

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

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

type View = 'all' | 'albums' | 'identities' | 'favorites';

function pickDeviceId(photos: readonly Photo[] | undefined): string | undefined {
  return photos?.[0]?.deviceId;
}

export function PhotosTab(): ReactElement {
  const [view, setView] = useState<View>('all');
  const [openAlbum, setOpenAlbum] = useState<Album | null>(null);

  // Single anchor query to discover the deviceId. The other sub-views key off
  // the same deviceId — single-device deployment, so this is fine.
  const allPhotos = usePhotos({ limit: 500 });
  const deviceId = pickDeviceId(allPhotos.data);

  const favorites = useMemo(
    () => (allPhotos.data ?? []).filter((p) => p.isFavorite),
    [allPhotos.data],
  );

  const headerTabs: Array<{ id: View; icon: ReactElement; label: string }> = [
    { id: 'all', icon: <Image size={14} />, label: 'All' },
    { id: 'albums', icon: <FolderOpen size={14} />, label: 'Albums' },
    { id: 'identities', icon: <Users size={14} />, label: 'People' },
    { id: 'favorites', icon: <Star size={14} />, label: 'Favorites' },
  ];

  return (
    <Root>
      <PageHeading>
        <Title>Photos</Title>
        <Tabs>
          {headerTabs.map((t) => (
            <TabButton
              key={t.id}
              $active={view === t.id && !openAlbum}
              onClick={() => {
                setView(t.id);
                setOpenAlbum(null);
              }}
            >
              {t.icon} {t.label}
            </TabButton>
          ))}
        </Tabs>
      </PageHeading>

      {openAlbum ? (
        <AlbumDetail album={openAlbum} onBack={() => setOpenAlbum(null)} />
      ) : view === 'all' ? (
        <>
          {allPhotos.isLoading && <SpinnerWrap aria-live="polite">Loading photos…</SpinnerWrap>}
          {allPhotos.error && <PageError message="Failed to load photos" />}
          {!allPhotos.isLoading && !allPhotos.error && (allPhotos.data?.length ?? 0) === 0 && (
            <EmptyState icon={<Image size={36} />} heading="No photos" sub="Photos will appear here once sync runs." />
          )}
          {!allPhotos.isLoading && !allPhotos.error && allPhotos.data && allPhotos.data.length > 0 && (
            <>
              <Meta>
                {allPhotos.data.length} photo{allPhotos.data.length !== 1 ? 's' : ''}
              </Meta>
              <PhotoGrid photos={allPhotos.data} />
            </>
          )}
        </>
      ) : view === 'albums' ? (
        <AlbumsView deviceId={deviceId} onAlbumClick={setOpenAlbum} />
      ) : view === 'identities' ? (
        <IdentitiesView deviceId={deviceId} />
      ) : (
        <>
          <Meta>
            {favorites.length} favorite{favorites.length !== 1 ? 's' : ''}
          </Meta>
          {favorites.length === 0 ? (
            <EmptyState icon={<Star size={36} />} heading="No favorites" sub="Stars in Photos.app show up here." />
          ) : (
            <PhotoGrid photos={favorites} ariaLabel="Favorite photos" />
          )}
        </>
      )}
    </Root>
  );
}
