import React, { useState, useEffect } from 'react';
import {
  MagnifyingGlassIcon,
  PlusIcon
} from '@heroicons/react/24/outline';
import { 
  MaterialCategory, 
  MaterialAsset,
  MaterialSelectorProps 
} from '../../types/videoGeneration';
import { SimpleMaterialCard } from './SimpleMaterialCard';

/**
 * 素材选择器组件
 * 支持从素材库中选择素材，支持多选和搜索
 */
export const MaterialSelector: React.FC<MaterialSelectorProps> = ({
  category,
  selectedAssets,
  onAssetsChange,
  maxSelection,
  allowMultiple = true
}) => {
  const [availableAssets, setAvailableAssets] = useState<MaterialAsset[]>([]);
  const [searchQuery, setSearchQuery] = useState('');
  const [filteredAssets, setFilteredAssets] = useState<MaterialAsset[]>([]);
  const [isLoading, setIsLoading] = useState(true);

  // 模拟素材数据
  const mockAssets: Record<MaterialCategory, MaterialAsset[]> = {
    [MaterialCategory.Model]: [
      {
        id: 'model_1',
        name: '时尚模特 - 杨明明',
        category: MaterialCategory.Model,
        type: 'image',
        file_path: '/assets/models/yangmingming.jpg',
        thumbnail_path: '/assets/thumbnails/yangmingming_thumb.jpg',
        description: '专业时尚模特，擅长各种风格拍摄',
        tags: ['时尚', '专业', '女性'],
        metadata: { width: 1920, height: 1080, size: 2048000, format: 'jpg' },
        created_at: '2024-01-15T10:00:00Z',
        updated_at: '2024-01-15T10:00:00Z'
      },
      {
        id: 'model_2',
        name: '商务模特 - 李小雅',
        category: MaterialCategory.Model,
        type: 'image',
        file_path: '/assets/models/lixiaoya.jpg',
        thumbnail_path: '/assets/thumbnails/lixiaoya_thumb.jpg',
        description: '专业商务模特，适合正装拍摄',
        tags: ['商务', '专业', '女性'],
        metadata: { width: 1920, height: 1080, size: 1856000, format: 'jpg' },
        created_at: '2024-01-16T10:00:00Z',
        updated_at: '2024-01-16T10:00:00Z'
      }
    ],
    [MaterialCategory.Product]: [
      {
        id: 'product_1',
        name: '夏季连衣裙',
        category: MaterialCategory.Product,
        type: 'image',
        file_path: '/assets/products/summer_dress.jpg',
        thumbnail_path: '/assets/thumbnails/summer_dress_thumb.jpg',
        description: '清新夏季连衣裙，多色可选',
        tags: ['连衣裙', '夏季', '清新'],
        metadata: { width: 1080, height: 1080, size: 1024000, format: 'jpg' },
        created_at: '2024-01-16T14:30:00Z',
        updated_at: '2024-01-16T14:30:00Z'
      },
      {
        id: 'product_2',
        name: '商务套装',
        category: MaterialCategory.Product,
        type: 'image',
        file_path: '/assets/products/business_suit.jpg',
        thumbnail_path: '/assets/thumbnails/business_suit_thumb.jpg',
        description: '经典商务套装，职场必备',
        tags: ['套装', '商务', '职场'],
        metadata: { width: 1080, height: 1080, size: 1152000, format: 'jpg' },
        created_at: '2024-01-17T14:30:00Z',
        updated_at: '2024-01-17T14:30:00Z'
      }
    ],
    [MaterialCategory.Scene]: [
      {
        id: 'scene_1',
        name: '现代简约客厅',
        category: MaterialCategory.Scene,
        type: 'image',
        file_path: '/assets/scenes/modern_living_room.jpg',
        thumbnail_path: '/assets/thumbnails/modern_living_room_thumb.jpg',
        description: '现代简约风格客厅背景',
        tags: ['现代', '简约', '客厅'],
        metadata: { width: 1920, height: 1080, size: 3072000, format: 'jpg' },
        created_at: '2024-01-17T09:15:00Z',
        updated_at: '2024-01-17T09:15:00Z'
      },
      {
        id: 'scene_2',
        name: '温馨卧室',
        category: MaterialCategory.Scene,
        type: 'image',
        file_path: '/assets/scenes/cozy_bedroom.jpg',
        thumbnail_path: '/assets/thumbnails/cozy_bedroom_thumb.jpg',
        description: '温馨舒适的卧室环境',
        tags: ['温馨', '卧室', '舒适'],
        metadata: { width: 1920, height: 1080, size: 2816000, format: 'jpg' },
        created_at: '2024-01-18T09:15:00Z',
        updated_at: '2024-01-18T09:15:00Z'
      }
    ],
    [MaterialCategory.Action]: [
      {
        id: 'action_1',
        name: '优雅姿态动作',
        category: MaterialCategory.Action,
        type: 'video',
        file_path: '/assets/actions/elegant_pose.mp4',
        thumbnail_path: '/assets/thumbnails/elegant_pose_thumb.jpg',
        description: '优雅的模特姿态动作参考',
        tags: ['优雅', '姿态', '动作'],
        metadata: { duration: 15, width: 1920, height: 1080, size: 5120000, format: 'mp4' },
        created_at: '2024-01-18T16:45:00Z',
        updated_at: '2024-01-18T16:45:00Z'
      }
    ],
    [MaterialCategory.Music]: [
      {
        id: 'music_1',
        name: '轻松背景音乐',
        category: MaterialCategory.Music,
        type: 'audio',
        file_path: '/assets/music/relaxing_bg.mp3',
        description: '轻松愉快的背景音乐',
        tags: ['轻松', '背景音乐', '愉快'],
        metadata: { duration: 120, size: 4096000, format: 'mp3' },
        created_at: '2024-01-19T11:20:00Z',
        updated_at: '2024-01-19T11:20:00Z'
      }
    ],
    [MaterialCategory.PromptTemplate]: [
      {
        id: 'prompt_1',
        name: '时尚穿搭提示词',
        category: MaterialCategory.PromptTemplate,
        type: 'text',
        description: '时尚穿搭AI生成提示词模板',
        tags: ['时尚', '穿搭', 'AI提示词'],
        created_at: '2024-01-20T13:10:00Z',
        updated_at: '2024-01-20T13:10:00Z'
      }
    ]
  };

  // 加载素材数据
  useEffect(() => {
    const loadAssets = async () => {
      setIsLoading(true);
      try {
        // 模拟API调用延迟
        await new Promise(resolve => setTimeout(resolve, 300));
        setAvailableAssets(mockAssets[category] || []);
      } catch (error) {
        console.error('Failed to load assets:', error);
      } finally {
        setIsLoading(false);
      }
    };

    loadAssets();
  }, [category]);

  // 过滤素材
  useEffect(() => {
    let filtered = availableAssets;

    if (searchQuery.trim()) {
      const query = searchQuery.toLowerCase();
      filtered = filtered.filter(asset => 
        asset.name.toLowerCase().includes(query) ||
        asset.description?.toLowerCase().includes(query) ||
        asset.tags.some(tag => tag.toLowerCase().includes(query))
      );
    }

    setFilteredAssets(filtered);
  }, [availableAssets, searchQuery]);

  // 处理素材选择
  const handleAssetSelect = (asset: MaterialAsset) => {
    const isSelected = selectedAssets.some(selected => selected.id === asset.id);
    
    if (isSelected) {
      // 取消选择
      const newSelection = selectedAssets.filter(selected => selected.id !== asset.id);
      onAssetsChange(newSelection);
    } else {
      // 选择素材
      if (allowMultiple) {
        if (maxSelection && selectedAssets.length >= maxSelection) {
          return; // 达到最大选择数量
        }
        onAssetsChange([...selectedAssets, asset]);
      } else {
        onAssetsChange([asset]);
      }
    }
  };

  // 检查素材是否已选择
  const isAssetSelected = (asset: MaterialAsset) => {
    return selectedAssets.some(selected => selected.id === asset.id);
  };

  return (
    <div className="h-full flex flex-col">
      {/* 搜索栏 */}
      <div className="flex-shrink-0 p-3 border-b border-gray-200">
        <div className="relative">
          <MagnifyingGlassIcon className="absolute left-3 top-1/2 transform -translate-y-1/2 h-3 w-3 text-gray-400" />
          <input
            type="text"
            placeholder="搜索..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="w-full pl-8 pr-3 py-1.5 border border-gray-200 rounded text-xs focus:ring-1 focus:ring-primary-500 focus:border-transparent transition-all duration-200"
          />
        </div>

        {/* 选择状态 */}
        {selectedAssets.length > 0 && (
          <div className="mt-2 text-xs text-gray-600 text-center">
            已选 {selectedAssets.length} 个
            {maxSelection && ` / ${maxSelection}`}
          </div>
        )}
      </div>

      {/* 素材列表 */}
      <div className="flex-1 overflow-y-auto p-3 custom-scrollbar">
        {isLoading ? (
          <div className="flex flex-col items-center justify-center h-32">
            <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-primary-600"></div>
            <span className="mt-2 text-xs text-gray-600">加载中...</span>
          </div>
        ) : filteredAssets.length === 0 ? (
          <div className="flex flex-col items-center justify-center h-32 text-gray-500">
            <PlusIcon className="h-6 w-6 mb-2 text-gray-300" />
            <p className="text-xs text-center">
              {searchQuery.trim() ? '未找到匹配的素材' : '暂无素材'}
            </p>
          </div>
        ) : (
          <div className="grid grid-cols-2 gap-2">
            {filteredAssets.map((asset) => (
              <SimpleMaterialCard
                key={asset.id}
                asset={asset}
                isSelected={isAssetSelected(asset)}
                onSelect={handleAssetSelect}
                onPreview={(asset) => {
                  console.log('Preview asset:', asset);
                  // TODO: 实现预览功能
                }}
              />
            ))}
          </div>
        )}
      </div>
    </div>
  );
};
