import React, { useEffect, useState, useCallback, useRef } from 'react';
import { useShallow } from 'zustand/react/shallow';
import { Card } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Search, Image as ImageIcon, MapPin, User, Box, Music, Loader2, Plus } from 'lucide-react';
import { Asset, AssetType, CharacterAsset, SceneAsset, PropAsset } from '@/types';
import { useProjectStore } from '@/lib/store/project';
import Image from 'next/image';
import { EmptyState } from '@/components/ui/empty-state';
import { DefaultService } from '@/lib/api';
import { useDebounce } from '@/lib/hooks/useDebounce';
import { useInView } from 'react-intersection-observer';
import { VirtualAssetGrid } from './VirtualAssetGrid';
import { SearchInput } from '@/components/ui/search-input';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";

interface AssetsTabProps {
  assetFilter: AssetType | 'all';
  assetSearch: string;
  setAssetFilter: (filter: AssetType | 'all') => void;
  setAssetSearch: (search: string) => void;
  setSelectedAsset: (asset: Asset | null) => void;
  onCreateAsset: (type: AssetType) => 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 AssetsTab: React.FC<AssetsTabProps> = ({
  assetFilter,
  assetSearch,
  setAssetFilter,
  setAssetSearch,
  setSelectedAsset,
  onCreateAsset
}) => {
  const { projectId, addAssets } = useProjectStore(
    useShallow((s) => ({ projectId: s.id, addAssets: s.addAssets }))
  );
  const [loading, setLoading] = useState(false);
  const [assets, setLocalAssets] = useState<Asset[]>([]);
  const [total, setTotal] = useState(0);
  const [offset, setOffset] = useState(0);
  const offsetRef = useRef(0);
  const LIMIT = 50;

  const debouncedSearch = useDebounce(assetSearch, 500);

  // Intersection Observer for Infinite Scroll
  const { ref, inView } = useInView({
    threshold: 0,
    rootMargin: '100px', // Preload when 100px from bottom
  });

  const fetchAssets = useCallback(async (isLoadMore: boolean = false) => {
    if (!projectId) return;
    const currentOffset = isLoadMore ? offsetRef.current : 0;

    setLoading(true);
    try {
      const response = await DefaultService.listProjectAssets(projectId);
      
      const data = (response as { data?: { assets: Asset[]; total: number } }).data;
      if (data) {
        if (isLoadMore) {
          setLocalAssets(prev => {
            const newAssets = [...prev, ...data.assets];
            addAssets(data.assets);
            return newAssets;
          });
          offsetRef.current += LIMIT;
          setOffset(prev => prev + LIMIT);
        } else {
          setLocalAssets(data.assets);
          addAssets(data.assets);
          setTotal(data.total);
          offsetRef.current = LIMIT;
          setOffset(LIMIT);
        }
      }
    } catch (error) {
      console.error("Failed to load assets:", error);
    } finally {
      setLoading(false);
    }
  }, [projectId, assetFilter, debouncedSearch, addAssets]);

  // Initial load and filter change（仅 projectId / 筛选 / 搜索 变化时拉取，避免因 offset 变化导致 fetchAssets 引用变化而重复刷新）
  useEffect(() => {
    offsetRef.current = 0;
    setOffset(0);
    fetchAssets(false);
  }, [projectId, assetFilter, debouncedSearch, fetchAssets]);

  const handleLoadMore = () => {
    fetchAssets(true);
  };

  const hasMore = assets.length < total;

  // Trigger load more when in view
  useEffect(() => {
    if (inView && hasMore && !loading) {
      fetchAssets(true);
    }
  }, [inView, hasMore, loading, fetchAssets]);

  const renderAssetInfo = (asset: Asset) => {
    switch (asset.type) {
      case 'character':
        const char = asset as CharacterAsset;
        return (
          <div className="flex gap-2 mt-1 text-[10px] text-muted-foreground">
             {char.gender && <span>{char.gender}</span>}
             {char.age && <span>{char.age}</span>}
             {char.role && <Badge variant="outline" className="text-[9px] h-4 px-1 py-0">{char.role}</Badge>}
          </div>
        );
      case 'scene':
        const scene = asset as SceneAsset;
        return (
          <div className="flex gap-2 mt-1 text-[10px] text-muted-foreground">
             {scene.location && <span className="truncate max-w-[80px]" title={scene.location}>{scene.location}</span>}
             {scene.timeOfDay && <span>• {scene.timeOfDay}</span>}
          </div>
        );
      case 'prop':
        const prop = asset as PropAsset;
        return prop.usage ? (
          <div className="mt-1 text-[10px] text-muted-foreground truncate" title={prop.usage}>
             {prop.usage}
          </div>
        ) : null;
      default:
        return null;
    }
  };

  // If assets exceed 500, use Virtual List for better performance
  if (assets.length > 500) {
    return (
      <div className="animate-in fade-in duration-300">
        <VirtualAssetGrid 
          assets={assets}
          onLoadMore={handleLoadMore}
          hasMore={hasMore}
          loading={loading}
          setSelectedAsset={setSelectedAsset}
        />
      </div>
    );
  }

  return (
    <div className="animate-in fade-in duration-300">
      {/* Header Controls */}
      <div className="flex items-center justify-between mb-6 gap-4">
        <div className="flex items-center gap-2">
          <Button 
            variant={assetFilter === 'all' ? "default" : "ghost"} 
            size="sm" 
            onClick={() => setAssetFilter('all')}
            className="rounded-full"
          >
            全部
          </Button>
          <Button 
            variant={assetFilter === 'character' ? "default" : "ghost"} 
            size="sm" 
            onClick={() => setAssetFilter('character')}
            className="rounded-full"
          >
            角色
          </Button>
          <Button 
            variant={assetFilter === 'scene' ? "default" : "ghost"} 
            size="sm" 
            onClick={() => setAssetFilter('scene')}
            className="rounded-full"
          >
            场景
          </Button>
          <Button 
            variant={assetFilter === 'prop' ? "default" : "ghost"} 
            size="sm" 
            onClick={() => setAssetFilter('prop')}
            className="rounded-full"
          >
            道具
          </Button>
        </div>
        <div className="flex items-center gap-2">
          <SearchInput
            value={assetSearch}
            onChange={setAssetSearch}
            placeholder="搜索素材..."
            className="w-64"
          />
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button size="sm" className="rounded-full gap-2">
                <Plus className="w-4 h-4" />
                创建素材
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end">
              <DropdownMenuItem onClick={() => onCreateAsset('character')}>
                创建角色
              </DropdownMenuItem>
              <DropdownMenuItem onClick={() => onCreateAsset('scene')}>
                创建场景
              </DropdownMenuItem>
              <DropdownMenuItem onClick={() => onCreateAsset('prop')}>
                创建道具
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
        </div>
      </div>

      {/* Content */}
      {assets.length > 0 ? (
        <>
          <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 2xl:grid-cols-6 gap-4">
            {assets.map(asset => {
               const Icon = ASSET_TYPE_ICONS[asset.type] || ImageIcon;
               return (
                <Card 
                  key={asset.id} 
                  className="group cursor-pointer overflow-hidden border-border/50 hover:border-primary/50 hover:shadow-md transition-all duration-300"
                  onClick={() => setSelectedAsset(asset)}
                >
                  <div className="aspect-square bg-muted/50 relative overflow-hidden">
                    {(asset.imageUrl || asset.imageUrls?.[0]) ? (
                      <Image 
                        src={asset.imageUrl || asset.imageUrls?.[0] || ''} 
                        alt={asset.name} 
                        fill
                        className="object-cover transition-transform duration-500 group-hover:scale-105"
                      />
                    ) : (
                      <div className="w-full h-full flex items-center justify-center text-muted-foreground/30">
                        <Icon className="w-10 h-10" />
                      </div>
                    )}
                    {/* Type Badge */}
                    <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">
                    <h4 className="font-medium truncate text-xs" title={asset.name}>{asset.name}</h4>
                    
                    {/* Dynamic Info based on Type */}
                    {renderAssetInfo(asset)}

                    {asset.tags && asset.tags.length > 0 && (
                      <div className="flex flex-wrap gap-1 mt-2">
                        {asset.tags.slice(0, 2).map(tag => (
                          <span key={tag} className="text-[10px] text-muted-foreground bg-muted px-1.5 py-0.5 rounded-sm">#{tag}</span>
                        ))}
                        {asset.tags.length > 2 && (
                          <span className="text-[10px] text-muted-foreground bg-muted px-1.5 py-0.5 rounded-sm">+{asset.tags.length - 2}</span>
                        )}
                      </div>
                    )}
                  </div>
                </Card>
              );
            })}
          </div>
          
          {hasMore && (
            <div ref={ref} className="flex justify-center mt-8 pb-4 min-h-[50px]">
                {loading && (
                    <>
                        <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                        <span className="text-sm text-muted-foreground">加载更多...</span>
                    </>
                )}
            </div>
          )}
        </>
      ) : (
        loading ? (
           <div className="flex justify-center py-20">
             <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
           </div>
        ) : (
          <EmptyState 
            icon={Search}
            title="未找到符合条件的素材"
            action={
              <Button variant="link" onClick={() => {setAssetFilter('all'); setAssetSearch('')}}>
                清除筛选
              </Button>
            }
            className="py-20"
          />
        )
      )}
    </div>
  );
};
