import React, { useState, useEffect } from 'react';
import { 
  MagnifyingGlassIcon, 
  PlusIcon,
  FunnelIcon,
  ViewColumnsIcon,
  Squares2X2Icon
} from '@heroicons/react/24/outline';
import { 
  MaterialCategory, 
  MaterialAsset, 
  MaterialCenterProps 
} from '../types/videoGeneration';
import { MaterialAssetCard } from '../components/video-generation/MaterialAssetCard';
import { MaterialCategoryFilter } from '../components/video-generation/MaterialCategoryFilter';
import { CreateMaterialAssetModal } from '../components/video-generation/CreateMaterialAssetModal';

/**
 * 素材中心页面
 * 遵循 Tauri 开发规范和 UI/UX 设计标准
 */
const MaterialCenter: React.FC<MaterialCenterProps> = ({
  selectedCategory,
  onCategoryChange,
  searchQuery = '',
  onSearchChange
}) => {
  const [assets, setAssets] = useState<MaterialAsset[]>([]);
  const [filteredAssets, setFilteredAssets] = useState<MaterialAsset[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid');
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [currentCategory, setCurrentCategory] = useState<MaterialCategory | undefined>(selectedCategory);
  const [currentSearchQuery, setCurrentSearchQuery] = useState(searchQuery);

  // 模拟数据 - 实际项目中应该从API获取
  const mockAssets: MaterialAsset[] = [
    {
      id: '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: '2',
      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: '3',
      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: '4',
      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'
    },
    {
      id: '5',
      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'
    },
    {
      id: '6',
      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, 500));
        setAssets(mockAssets);
      } catch (error) {
        console.error('Failed to load assets:', error);
      } finally {
        setIsLoading(false);
      }
    };

    loadAssets();
  }, []);

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

    // 按分类过滤
    if (currentCategory) {
      filtered = filtered.filter(asset => asset.category === currentCategory);
    }

    // 按搜索关键词过滤
    if (currentSearchQuery.trim()) {
      const query = currentSearchQuery.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);
  }, [assets, currentCategory, currentSearchQuery]);

  // 处理分类变化
  const handleCategoryChange = (category: MaterialCategory | undefined) => {
    setCurrentCategory(category);
    category && onCategoryChange?.(category);
  };

  // 处理搜索变化
  const handleSearchChange = (query: string) => {
    setCurrentSearchQuery(query);
    onSearchChange?.(query);
  };

  // 处理素材操作
  const handleAssetPreview = (asset: MaterialAsset) => {
    console.log('Preview asset:', asset);
    // TODO: 实现预览功能
  };

  const handleAssetEdit = (asset: MaterialAsset) => {
    console.log('Edit asset:', asset);
    // TODO: 实现编辑功能
  };

  const handleAssetDelete = (asset: MaterialAsset) => {
    console.log('Delete asset:', asset);
    // TODO: 实现删除功能
  };

  const handleCreateAsset = () => {
    setShowCreateModal(true);
  };

  return (
    <div className="app-layout bg-gradient-to-br from-gray-50 via-white to-gray-50">
      {/* 页面标题和操作栏 */}
      <div className="app-header page-header">
        <div className="flex items-center justify-between">
          <div className="relative z-10">
            <h1 className="text-heading-2 text-gradient-primary">
              素材中心
            </h1>
            <p className="text-body-small text-medium-emphasis mt-1">
              管理和组织视频生成所需的各类素材资源
            </p>
          </div>

          <div className="flex items-center gap-3 relative z-10">
            {/* 视图切换 */}
            <div className="flex items-center bg-white/80 backdrop-blur-sm rounded-lg p-1 shadow-soft border border-gray-200/50">
              <button
                onClick={() => setViewMode('grid')}
                className={`p-2 rounded-md transition-all duration-200 touch-target ${
                  viewMode === 'grid'
                    ? 'bg-primary-100 text-primary-700 shadow-subtle'
                    : 'text-gray-500 hover:text-gray-700 hover:bg-gray-50'
                }`}
                title="网格视图"
              >
                <Squares2X2Icon className="h-4 w-4" />
              </button>
              <button
                onClick={() => setViewMode('list')}
                className={`p-2 rounded-md transition-all duration-200 touch-target ${
                  viewMode === 'list'
                    ? 'bg-primary-100 text-primary-700 shadow-subtle'
                    : 'text-gray-500 hover:text-gray-700 hover:bg-gray-50'
                }`}
                title="列表视图"
              >
                <ViewColumnsIcon className="h-4 w-4" />
              </button>
            </div>

            {/* 添加素材按钮 */}
            <button
              onClick={handleCreateAsset}
              className="flex items-center gap-2 px-4 py-2 bg-gradient-primary text-white rounded-lg hover:shadow-medium transition-all duration-200 hover-lift touch-target"
            >
              <PlusIcon className="h-4 w-4" />
              <span className="text-body-small font-medium">添加素材</span>
            </button>
          </div>
        </div>
      </div>

      {/* 搜索和过滤栏 */}
      <div className="flex-shrink-0 glass-effect border-b border-gray-200/30 px-6 py-4">
        <div className="flex items-center gap-4">
          {/* 搜索框 */}
          <div className="flex-1 relative">
            <MagnifyingGlassIcon className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
            <input
              type="text"
              placeholder="搜索素材名称、描述或标签..."
              value={currentSearchQuery}
              onChange={(e) => handleSearchChange(e.target.value)}
              className="w-full pl-10 pr-4 py-2 border border-gray-200/50 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-primary-300 transition-all duration-200 bg-white/90 backdrop-blur-sm shadow-subtle touch-target"
            />
          </div>

          {/* 分类过滤器 */}
          <MaterialCategoryFilter
            selectedCategory={currentCategory}
            onCategoryChange={handleCategoryChange}
          />
        </div>
      </div>

      {/* 素材列表 */}
      <div className="app-main content-container custom-scrollbar">
        {isLoading ? (
          <div className="flex-center h-64">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-600"></div>
            <span className="ml-3 text-medium-emphasis">加载素材中...</span>
          </div>
        ) : filteredAssets.length === 0 ? (
          <div className="flex-center flex-col h-64 text-low-emphasis">
            <FunnelIcon className="h-12 w-12 mb-4 text-gray-300" />
            <p className="text-heading-6 text-high-emphasis">暂无素材</p>
            <p className="text-body-small text-center max-w-md">
              {currentCategory || currentSearchQuery.trim()
                ? '尝试调整筛选条件或搜索关键词'
                : '点击"添加素材"开始创建您的第一个素材'
              }
            </p>
          </div>
        ) : (
          <div className={
            viewMode === 'grid'
              ? 'material-grid animate-fade-in'
              : 'space-y-4 animate-fade-in'
          }>
            {filteredAssets.map((asset, index) => (
              <div
                key={asset.id}
                className="animate-slide-up"
                style={{ animationDelay: `${index * 50}ms` }}
              >
                <MaterialAssetCard
                  asset={asset}
                  viewMode={viewMode}
                  onPreview={handleAssetPreview}
                  onEdit={handleAssetEdit}
                  onDelete={handleAssetDelete}
                  showActions={true}
                />
              </div>
            ))}
          </div>
        )}
      </div>

      {/* 创建素材模态框 */}
      {showCreateModal && (
        <CreateMaterialAssetModal
          isOpen={showCreateModal}
          onClose={() => setShowCreateModal(false)}
          onAssetCreated={(asset) => {
            setAssets(prev => [asset, ...prev]);
            setShowCreateModal(false);
          }}
        />
      )}
    </div>
  );
};

export default MaterialCenter;
