'use client';

import { useState } from 'react';
import { Trash2, Image, Video, ExternalLink } from 'lucide-react';

export interface MediaItem {
  id: string;
  path: string;
  url: string;
  filename: string;
  contentType: string;
  size: number;
  createdAt: string;
}

export interface MediaLibraryProps {
  /** Media items to display */
  items: MediaItem[];
  /** Called when a media item is deleted (by ID) */
  onDelete?: (id: string) => void;
  /** Called when a media item is selected */
  onSelect?: (item: MediaItem) => void;
  /** Whether delete operations are in progress */
  isDeleting?: boolean;
  /** Show empty state */
  emptyMessage?: string;
}

function formatSize(bytes: number): string {
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}

function isImage(contentType: string): boolean {
  return contentType.startsWith('image/');
}

function isVideo(contentType: string): boolean {
  return contentType.startsWith('video/');
}

export function MediaLibrary({
  items,
  onDelete,
  onSelect,
  isDeleting = false,
  emptyMessage = 'No media files yet. Upload or generate some!',
}: MediaLibraryProps) {
  const [selectedId, setSelectedId] = useState<string | null>(null);

  if (items.length === 0) {
    return (
      <div className="text-center py-12 text-[var(--text-muted)]">
        <Image className="h-12 w-12 mx-auto mb-3 opacity-50" />
        <p className="text-sm">{emptyMessage}</p>
      </div>
    );
  }

  return (
    <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
      {items.map((item) => (
        <div
          key={item.id}
          className={`
            group relative rounded-lg overflow-hidden border transition-colors cursor-pointer
            ${selectedId === item.id
              ? 'border-[var(--accent)] ring-2 ring-[var(--accent)]/20'
              : 'border-[var(--border-muted)] hover:border-[var(--border-default)]'}
          `}
          onClick={() => {
            setSelectedId(item.id);
            onSelect?.(item);
          }}
        >
          {/* Preview */}
          <div className="aspect-square bg-[var(--surface-200)] flex items-center justify-center overflow-hidden">
            {isImage(item.contentType) ? (
              <img
                src={item.url}
                alt={item.filename || item.path.split('/').pop() || ''}
                className="w-full h-full object-cover"
                loading="lazy"
              />
            ) : isVideo(item.contentType) ? (
              <video
                src={item.url}
                className="w-full h-full object-cover"
                muted
                playsInline
                onMouseOver={(e) => (e.target as HTMLVideoElement).play()}
                onMouseOut={(e) => { const v = e.target as HTMLVideoElement; v.pause(); v.currentTime = 0; }}
              />
            ) : (
              <div className="text-[var(--text-muted)]">
                <Image className="h-8 w-8" />
              </div>
            )}
          </div>

          {/* Info bar */}
          <div className="p-2 bg-[var(--surface-100)]">
            <p className="text-xs text-[var(--text-primary)] truncate">
              {item.filename || item.path.split('/').pop()}
            </p>
            <p className="text-xs text-[var(--text-muted)]">
              {formatSize(item.size)}
            </p>
          </div>

          {/* Overlay actions */}
          <div className="absolute top-2 right-2 flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
            <a
              href={item.url}
              target="_blank"
              rel="noopener noreferrer"
              onClick={(e) => e.stopPropagation()}
              className="p-1.5 rounded bg-black/60 text-white hover:bg-black/80"
              title="Open in new tab"
            >
              <ExternalLink className="h-3.5 w-3.5" />
            </a>
            {onDelete && (
              <button
                onClick={(e) => { e.stopPropagation(); onDelete(item.id); }}
                disabled={isDeleting}
                className="p-1.5 rounded bg-black/60 text-white hover:bg-red-600"
                title="Delete"
              >
                <Trash2 className="h-3.5 w-3.5" />
              </button>
            )}
          </div>

          {/* Type badge */}
          <div className="absolute top-2 left-2">
            {isVideo(item.contentType) ? (
              <span className="flex items-center gap-1 px-1.5 py-0.5 rounded bg-black/60 text-white text-xs">
                <Video className="h-3 w-3" /> Video
              </span>
            ) : null}
          </div>
        </div>
      ))}
    </div>
  );
}
