import * as React from 'react';
import { cn } from '../utils/cn';
import { AnchorPreview } from './AnchorPreview';
import { ShotCard } from './ShotCard';

export type ShotStatus = 'pending' | 'generating' | 'complete' | 'failed';

export interface AlbumShot {
  index: number;
  label: string;
  direction: string;
  imageUrl: string;
  status: ShotStatus;
  error?: string;
}

export interface AlbumGridProps extends React.HTMLAttributes<HTMLDivElement> {
  /** Album name */
  name?: string;
  /** Anchor image URL — empty string if not yet generated */
  anchorUrl?: string;
  /** Whether the anchor is currently being generated */
  anchorGenerating?: boolean;
  /** The list of shots in the album */
  shots: AlbumShot[];
  /** Number of columns (default: auto 3-4 based on screen) */
  columns?: 3 | 4 | 5;
  /** Called when the user requests anchor generation */
  onGenerateAnchor?: () => void;
  /** Called when the user requests anchor regeneration */
  onRegenerateAnchor?: () => void;
  /** Called when the user requests generation of all pending shots */
  onGenerateAllShots?: () => void;
  /** Called when the user requests regeneration of a specific shot */
  onRegenerateShot?: (index: number) => void;
  /** Called when the user resets a shot back to pending */
  onResetShot?: (index: number) => void;
  /** Called when the user clicks an image (e.g., to open lightbox) */
  onImageClick?: (index: number | 'anchor') => void;
}

/**
 * AlbumGrid displays an album as a responsive image grid.
 *
 * Layout:
 * ┌──────────────┬──────────────┬──────────────┬──────────────┐
 * │  [Anchor]    │  Headshot    │   Casual     │ Professional │
 * │  Reference   │  [shimmer]   │ ✓ [image]   │  ✓ [image]  │
 * ├──────────────┼──────────────┼──────────────┼──────────────┤
 * │   Candid     │   Outdoor    │  Editorial   │              │
 * │  [pending]   │  [pending]   │  [pending]   │              │
 * └──────────────┴──────────────┴──────────────┴──────────────┘
 *
 * - Anchor occupies the first slot with accent styling
 * - Pending shots show the label + "Generate" button (disabled until anchor ready)
 * - Generating shots show a shimmer animation
 * - Complete shots show the image with hover controls
 *
 * @example
 * ```tsx
 * <AlbumGrid
 *   anchorUrl={album.anchorUrl}
 *   shots={album.shots}
 *   onGenerateAnchor={generateAnchor}
 *   onGenerateAllShots={generateAllShots}
 *   onRegenerateShot={regenerateShot}
 *   onResetShot={resetShot}
 * />
 * ```
 */
const AlbumGrid = React.forwardRef<HTMLDivElement, AlbumGridProps>(
  (
    {
      name,
      anchorUrl,
      anchorGenerating = false,
      shots,
      columns = 4,
      onGenerateAnchor,
      onRegenerateAnchor,
      onGenerateAllShots,
      onRegenerateShot,
      onResetShot,
      onImageClick,
      className,
      ...props
    },
    ref
  ) => {
    const anchorReady = !!anchorUrl;
    const pendingShots = shots.filter((s) => s.status === 'pending' || s.status === 'failed');
    const allComplete = shots.every((s) => s.status === 'complete');

    const colClass =
      columns === 3
        ? 'grid-cols-3'
        : columns === 5
        ? 'grid-cols-2 sm:grid-cols-3 md:grid-cols-5'
        : 'grid-cols-2 sm:grid-cols-3 md:grid-cols-4';

    return (
      <div ref={ref} className={cn('space-y-3', className)} {...props}>
        {/* Header row with name + action buttons */}
        {(name || onGenerateAllShots) && (
          <div className="flex items-center justify-between gap-2">
            {name && (
              <h3 className="text-sm font-semibold text-[var(--text-primary)]">{name}</h3>
            )}
            <div className="flex items-center gap-2 ml-auto">
              {onGenerateAllShots && anchorReady && pendingShots.length > 0 && (
                <button
                  onClick={onGenerateAllShots}
                  className="px-3 py-1.5 text-xs rounded-md bg-[var(--accent)] text-white hover:opacity-80 transition-opacity font-medium"
                >
                  Generate All ({pendingShots.length})
                </button>
              )}
              {allComplete && (
                <span className="text-xs text-[var(--text-secondary)]">
                  ✓ All complete
                </span>
              )}
            </div>
          </div>
        )}

        {/* Grid */}
        <div className={cn('grid gap-2', colClass)}>
          {/* Anchor slot — always first */}
          <AnchorPreview
            anchorUrl={anchorUrl}
            isGenerating={anchorGenerating}
            label="Reference"
            onGenerate={onGenerateAnchor}
            onRegenerate={onRegenerateAnchor}
            onImageClick={onImageClick ? () => onImageClick('anchor') : undefined}
          />

          {/* Shot slots */}
          {shots.map((shot) => (
            <ShotCard
              key={shot.index}
              label={shot.label}
              status={shot.status}
              imageUrl={shot.imageUrl}
              error={shot.error}
              anchorReady={anchorReady}
              onGenerate={onRegenerateShot ? () => onRegenerateShot(shot.index) : undefined}
              onRegenerate={onRegenerateShot ? () => onRegenerateShot(shot.index) : undefined}
              onReset={onResetShot ? () => onResetShot(shot.index) : undefined}
              onImageClick={onImageClick ? () => onImageClick(shot.index) : undefined}
            />
          ))}
        </div>
      </div>
    );
  }
);
AlbumGrid.displayName = 'AlbumGrid';

export { AlbumGrid };
