import { Card } from '@/components/ui/card';
import { Folder, Music, Image as ImageIcon, File, CheckSquare, Square } from 'lucide-react';
import type { FileNode } from './types';
import { cn } from '@/lib/utils';

interface FileManagerViewGridProps {
  files: FileNode[];
  selectedIds: string[];
  onToggleSelect: (id: string) => void;
  onFileClick: (file: FileNode) => void;
}

function FileTypeIcon({ type, size = 'md' }: { type: FileNode['type']; size?: 'md' | 'lg' }) {
  const cl = size === 'lg' ? 'w-8 h-8' : 'w-5 h-5';
  if (type === 'folder') return <Folder className={cn(cl, 'text-primary')} />;
  if (type === 'audio') return <Music className={cn(cl, 'text-muted-foreground')} />;
  if (type === 'image') return <ImageIcon className={cn(cl, 'text-secondary')} />;
  if (['document', 'archive', 'project'].includes(type)) {
    return <File className={cn(cl, 'text-muted-foreground')} />;
  }
  return <File className={cn(cl, 'text-muted-foreground')} />;
}

export function FileManagerViewGrid({
  files,
  selectedIds,
  onToggleSelect,
  onFileClick,
}: FileManagerViewGridProps) {
  return (
    <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-5 gap-4">
      {files.map((file) => (
        <Card
          key={file.id}
          variant="default"
          className={cn(
            'p-4 flex flex-col items-center text-center gap-4 cursor-pointer hover:border-primary/50 transition-all group relative',
            selectedIds.includes(file.id) && 'border-primary bg-primary/5',
          )}
          onClick={() => onFileClick(file)}
        >
          <button
            type="button"
            className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity z-10"
            onClick={(e) => {
              e.stopPropagation();
              onToggleSelect(file.id);
            }}
            aria-label={selectedIds.includes(file.id) ? 'Deselect' : 'Select'}
          >
            {selectedIds.includes(file.id) ? (
              <CheckSquare className="w-4 h-4 text-primary" />
            ) : (
              <Square className="w-4 h-4 text-muted-foreground hover:text-white" />
            )}
          </button>
          <div className="w-16 h-16 rounded-2xl bg-muted flex items-center justify-center shadow-lg transition-colors duration-200">
            <FileTypeIcon type={file.type} size="lg" />
          </div>
          <div className="w-full min-w-0">
            <h4 className="font-bold text-white text-sm truncate w-full">
              {file.name}
            </h4>
            <p className="text-xs text-muted-foreground mt-1">{file.size}</p>
          </div>
        </Card>
      ))}
    </div>
  );
}
