'use client';

/**
 * Grille présentationnelle des médias. Composant pur : ne fait pas de fetch.
 * Utilisé à la fois par la page admin et par le MediaPicker.
 */

import { Image01Icon, Pdf02Icon, Mp402Icon, Mp302Icon, File02Icon, UserGroupIcon, BlockedIcon, Tick02Icon } from '@zen/core/shared/icons';
import MediaImage from './MediaImage.client.js';

const KIND_ICON = {
  'image/jpeg':       Image01Icon,
  'image/png':        Image01Icon,
  'image/gif':        Image01Icon,
  'image/webp':       Image01Icon,
  'application/pdf':  Pdf02Icon,
  'video/mp4':        Mp402Icon,
  'audio/mpeg':       Mp302Icon,
};

function iconForMime(mimeType) {
  return KIND_ICON[mimeType] ?? File02Icon;
}

function isImage(mimeType) {
  return typeof mimeType === 'string' && mimeType.startsWith('image/');
}

function formatSize(bytes) {
  if (!Number.isFinite(bytes)) return '';
  if (bytes < 1024) return `${bytes} o`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} Ko`;
  return `${(bytes / (1024 * 1024)).toFixed(1)} Mo`;
}

export default function MediaGrid({
  items = [],
  loading = false,
  onSelect,
  selectedIds = new Set(),
  emptyMessage = 'Aucun média',
}) {
  if (loading && items.length === 0) {
    return (
      <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-3">
        {Array.from({ length: 12 }).map((_, i) => (
          <div key={i} className="aspect-square rounded-lg bg-neutral-100 dark:bg-neutral-900 animate-pulse" />
        ))}
      </div>
    );
  }

  if (items.length === 0) {
    return (
      <div className="py-16 text-center text-sm text-neutral-500 dark:text-neutral-400">
        {emptyMessage}
      </div>
    );
  }

  return (
    <div className={`grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-3 transition-opacity ${loading ? 'opacity-60' : ''}`}>
      {items.map(media => {
        const Icon = iconForMime(media.mime_type);
        const isSelected = selectedIds.has(media.id);

        return (
          <button
            key={media.id}
            type="button"
            onClick={() => onSelect?.(media)}
            className={`
              group relative flex flex-col items-stretch
              rounded-lg overflow-hidden
              border ${isSelected ? 'border-blue-500 ring-2 ring-blue-500/40' : 'border-neutral-200 dark:border-neutral-800'}
              bg-white dark:bg-[#0B0B0B]
              text-left transition-colors
              hover:border-neutral-300 dark:hover:border-neutral-700
            `}
          >
            <div className="relative aspect-square bg-neutral-50 dark:bg-neutral-950 flex items-center justify-center overflow-hidden">
              {isImage(media.mime_type) ? (
                <MediaImage
                  media={media}
                  fill
                  sizes="(max-width: 640px) 50vw, (max-width: 1024px) 33vw, 16vw"
                  className="object-cover"
                />
              ) : (
                <Icon className="w-10 h-10 text-neutral-400" />
              )}
            </div>
            <div className="px-2 py-1.5 text-[11px] leading-tight">
              <div className="truncate text-neutral-900 dark:text-white" title={media.original_name}>
                {media.original_name}
              </div>
              <div className="mt-0.5 flex items-center gap-1.5 text-neutral-500 dark:text-neutral-400">
                {media.visibility === 'public' ? (
                  <span className="inline-flex items-center gap-0.5"><UserGroupIcon className="w-3 h-3" /> Public</span>
                ) : (
                  <span className="inline-flex items-center gap-0.5"><BlockedIcon className="w-3 h-3" /> Privé</span>
                )}
                <span>·</span>
                <span>{formatSize(Number(media.size_bytes))}</span>
              </div>
            </div>
            {isSelected && (
              <div className="absolute top-1.5 right-1.5 rounded-full bg-blue-500 text-white p-0.5">
                <Tick02Icon className="w-3 h-3" />
              </div>
            )}
          </button>
        );
      })}
    </div>
  );
}
