import React from 'react';
import { Asset } from '@/types';
import { Card } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { User, MapPin, Box, Music, Image as ImageIcon, Loader2 } from 'lucide-react';
import Image from 'next/image';
import { Grid } from 'react-window';
const { AutoSizer } = require('react-virtualized-auto-sizer');

interface VirtualAssetGridProps {
  assets: Asset[];
  onLoadMore: () => void;
  hasMore: boolean;
  loading: boolean;
  setSelectedAsset: (asset: Asset | null) => void;
}

const ASSET_TYPE_LABELS: Record<string, string> = {
  character: '角色',
  scene: '场景',
  prop: '道具',
  audio: '音频',
  other: '其他'
};

const ASSET_TYPE_ICONS: Record<string, React.ElementType> = {
  character: User,
  scene: MapPin,
  prop: Box,
  audio: Music,
  other: ImageIcon
};

export const VirtualAssetGrid: React.FC<VirtualAssetGridProps> = ({
  assets,
  onLoadMore,
  hasMore,
  loading,
  setSelectedAsset
}) => {
  const getColumnCount = (width: number) => {
    if (width >= 1536) return 6; // 2xl
    if (width >= 1280) return 5; // xl
    if (width >= 1024) return 4; // lg
    if (width >= 768) return 3;  // md
    return 2;                    // default
  };

  const GAP = 16; 

  // The Cell component now receives custom props directly spread from cellProps
  const Cell = ({ columnIndex, rowIndex, style, assets, columnCount, setSelectedAsset }: any) => {
    const index = rowIndex * columnCount + columnIndex;
    
    if (index >= assets.length) return null;
    
    const asset = assets[index];
    const Icon = ASSET_TYPE_ICONS[asset.type] || ImageIcon;

    const itemStyle = {
      ...style,
      left: Number(style.left) + GAP / 2,
      top: Number(style.top) + GAP / 2,
      width: Number(style.width) - GAP,
      height: Number(style.height) - GAP,
    };

    return (
      <div style={itemStyle}>
        <Card 
            className="group cursor-pointer overflow-hidden border-border/50 hover:border-primary/50 hover:shadow-md transition-all duration-300 h-full flex flex-col"
            onClick={() => setSelectedAsset(asset)}
        >
            <div className="aspect-square bg-muted/50 relative overflow-hidden shrink-0">
            {asset.imageUrl ? (
                <Image 
                src={asset.imageUrl} 
                alt={asset.name} 
                fill
                className="object-cover transition-transform duration-500 group-hover:scale-105"
                sizes="(max-width: 768px) 50vw, (max-width: 1200px) 33vw, 20vw"
                />
            ) : (
                <div className="w-full h-full flex items-center justify-center text-muted-foreground/30">
                <Icon className="w-10 h-10" />
                </div>
            )}
            <div className="absolute top-2 right-2">
                <Badge variant="secondary" className="backdrop-blur-md bg-background/80 shadow-sm text-xs font-normal">
                {ASSET_TYPE_LABELS[asset.type] || asset.type}
                </Badge>
            </div>
            </div>
            <div className="p-3 flex flex-col flex-1 min-h-0">
                <h4 className="font-medium truncate text-xs" title={asset.name}>{asset.name}</h4>
                <div className="flex-1"></div>
                
                {asset.tags && asset.tags.length > 0 && (
                    <div className="flex flex-wrap gap-1 mt-2 overflow-hidden max-h-[22px]">
                    {asset.tags.slice(0, 2).map((tag: string) => (
                        <span key={tag} className="text-[10px] text-muted-foreground bg-muted px-1.5 py-0.5 rounded-sm truncate max-w-[60px]">#{tag}</span>
                    ))}
                    </div>
                )}
            </div>
        </Card>
      </div>
    );
  };

  return (
    <div className="h-[calc(100vh-250px)] w-full"> 
      <AutoSizer>
        {({ height, width }: { height: number; width: number }) => {
          if (height === undefined || width === undefined) return null;

          const columnCount = getColumnCount(width);
          const columnWidth = width / columnCount;
          const rowHeight = columnWidth + 80;
          const rowCount = Math.ceil(assets.length / columnCount);

          return (
            <Grid
              columnCount={columnCount}
              columnWidth={columnWidth}
              style={{ height, width }}
              rowCount={rowCount}
              rowHeight={rowHeight}
              cellComponent={Cell}
              cellProps={{ assets, columnCount, setSelectedAsset }}
              onCellsRendered={({ rowStopIndex }: { rowStopIndex: number }) => {
                if (hasMore && !loading && rowStopIndex > rowCount - 3) {
                  onLoadMore();
                }
              }}
            >
            </Grid>
          );
        }}
      </AutoSizer>
      {loading && (
        <div className="absolute bottom-4 left-1/2 transform -translate-x-1/2 bg-background/80 p-2 rounded-full shadow-lg backdrop-blur">
          <Loader2 className="h-5 w-5 animate-spin text-primary" />
        </div>
      )}
    </div>
  );
};
