import { useQuery } from '@tanstack/react-query'
import { api, GalleryGroupCard } from '../../lib/api'
import { THUMB_CACHE_V } from '../../lib/utils'
import { Loader2, Image as ImageIcon, Users } from 'lucide-react'

interface Props {
  onSelectGroup: (groupId: number) => void
}

export default function GalleryGroupLanding({ onSelectGroup }: Props) {
  const { data: groups, isLoading } = useQuery({
    queryKey: ['gallery-groups'],
    queryFn: () => api.paidContent.getGalleryGroups(),
  })

  // Calculate total media across all groups
  const totalMedia = groups?.reduce((sum, g) => sum + g.total_media, 0) ?? 0

  if (isLoading) {
    return (
      <div className="flex items-center justify-center py-20">
        <Loader2 className="w-8 h-8 animate-spin text-muted-foreground" />
      </div>
    )
  }

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold">Gallery</h1>
        <p className="text-muted-foreground mt-1">Browse media by group</p>
      </div>

      <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
        {/* All Media card */}
        <button
          type="button"
          className="relative aspect-[4/3] bg-secondary rounded-xl overflow-hidden cursor-pointer group transition-all hover:ring-2 hover:ring-primary"
          onClick={() => onSelectGroup(0)}
        >
          <div className="absolute inset-0 bg-gradient-to-br from-primary/20 to-primary/5 flex items-center justify-center">
            <ImageIcon className="w-12 h-12 text-primary/40" />
          </div>
          <div className="absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/80 via-black/50 to-transparent p-4">
            <div className="text-white font-semibold text-lg">All Media</div>
            <div className="text-white/70 text-sm">{totalMedia.toLocaleString()} items</div>
          </div>
        </button>

        {/* Group cards */}
        {groups?.map((group: GalleryGroupCard) => (
          <button
            key={group.id}
            type="button"
            className="relative aspect-[4/3] bg-secondary rounded-xl overflow-hidden cursor-pointer group transition-all hover:ring-2 hover:ring-primary"
            onClick={() => onSelectGroup(group.id)}
          >
            {group.representative_attachment_id ? (
              <img
                src={`/api/paid-content/files/thumbnail/${group.representative_attachment_id}?size=large&${THUMB_CACHE_V}`}
                alt=""
                className="w-full h-full object-cover transition-transform group-hover:scale-105"
                loading="lazy"
                onError={(e) => {
                  (e.target as HTMLImageElement).style.display = 'none'
                }}
              />
            ) : (
              <div className="w-full h-full flex items-center justify-center">
                <ImageIcon className="w-12 h-12 text-muted-foreground/30" />
              </div>
            )}
            <div className="absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/80 via-black/50 to-transparent p-4">
              <div className="text-white font-semibold text-lg truncate">{group.name}</div>
              <div className="text-white/70 text-sm flex items-center gap-2">
                <Users className="w-3.5 h-3.5" />
                {group.member_count} creator{group.member_count !== 1 ? 's' : ''}
                <span className="mx-1">·</span>
                {group.total_media.toLocaleString()} items
              </div>
            </div>
          </button>
        ))}
      </div>

      {groups && groups.length === 0 && (
        <div className="text-center py-12 text-muted-foreground">
          No creator groups found. Create groups in the Creators page first.
        </div>
      )}
    </div>
  )
}
