import React, { useState, useEffect, useRef, useCallback } from 'react';
import { Card, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
import { Upload, User, Shirt, HelpCircle, Trash2, Edit, X } from 'lucide-react';
import { materialLibraryAPI } from '@/api/materials';
import { useAuth } from '@/contexts/AuthContext';
import { toast } from 'sonner';
import MaterialCard from '@/components/MaterialCard';

// 自定义图标组件
const TShirtIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <path d="M20.38 3.46 16 2a4 4 0 0 1-8 0L3.62 3.46a2 4 0 0 0-1.34 2.23l.58 3.47a1 1 0 0 0 .99.84H6v10c0 1.1.9 2 2 2h8a2 4 0 0 0 2-2V10h2.15a1 1 0 0 0 .99-.84l.58-3.47a2 4 0 0 0-1.34-2.23z"></path>
  </svg>
);

const PersonIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path>
    <circle cx="12" cy="7" r="4"></circle>
  </svg>
);

const UploadIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
    <polyline points="7,10 12,15 17,10"></polyline>
    <line x1="12" y1="15" x2="12" y2="3"></line>
  </svg>
);

// 统一的素材类型映射函数
const getMaterialType = (activeTab) => {
  switch (activeTab) {
    case 'face':
      return 'face';
    case 'product':
      return 'cloth';
    // case 'result':
    //   return 'original';
    case 'original':
      return 'original';
    default:
      return null;
  }
};

export default function MaterialLibrary() {
  const { user } = useAuth();
  const [activeTab, setActiveTab] = useState('face');
  const [materials, setMaterials] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [isUploading, setIsUploading] = useState(false);
  const fileInputRef = useRef(null);
  const dropZoneRef = useRef(null);

  // 加载素材数据
  useEffect(() => {
    if (user?.id) {
      loadMaterials(user.id);
    } else {
      toast.error('请先登录');
    }
  }, [activeTab, user]);

  const loadMaterials = async (userId) => {
    if (!userId) {
      toast.error('请先登录');
      return;
    }
    
    setIsLoading(true);
    try {
      // 使用统一的素材类型映射函数
      const materialType = getMaterialType(activeTab);
      console.log('加载素材，用户ID:', userId, '类型:', materialType);
      const response = await materialLibraryAPI.getMaterials(userId, materialType);
      console.log('API响应:', response);
      
      if (response.success) {
        // 使用与旧版本兼容的数据格式
        const materials = (response.images || []).map(item => ({
          id: item.id,
          name: item.original_filename?.split('.')[0] || '未命名',
          original_filename: item.original_filename,
          stored_path: item.stored_path,
          image_type: item.image_type,
          created_at: item.created_at
        }));
        console.log('处理后的素材数据:', materials);
        setMaterials(materials);
      } else {
        console.error('API返回失败:', response);
        toast.error('加载素材失败');
      }
    } catch (error) {
      console.error('加载素材失败:', error);
      toast.error('加载素材失败');
    } finally {
      setIsLoading(false);
    }
  };

  // 文件上传处理
  const handleFileUpload = async (files) => {
    if (!user?.id) {
      toast.error('请先登录');
      return;
    }

    setIsUploading(true);
    const uploadPromises = Array.from(files).map(async (file) => {
      try {
        // 检查文件类型和大小
        const allowedTypes = ['image/png', 'image/jpg', 'image/jpeg'];
        if (!allowedTypes.includes(file.type)) {
          throw new Error('不支持的文件格式，仅支持PNG、JPG、JPEG格式');
        }

        if (file.size > 200 * 1024 * 1024) { // 200MB
          throw new Error('文件大小不能超过200MB');
        }

        // 使用统一的素材类型映射函数
        const imageType = getMaterialType(activeTab);
        console.log('开始上传文件:', file.name, '类型:', imageType, '标签页:', activeTab);
        
        const response = await materialLibraryAPI.uploadMaterial(
          user.id,
          file,
          imageType,
          file.name
        );
        
        console.log('上传响应:', response);

        if (response.success) {
          return {
            success: true,
            material_id: response.material_id,
            original_filename: response.original_filename
          };
        } else {
          throw new Error(response.error || '上传失败');
        }
      } catch (error) {
        console.error('文件上传失败:', error);
        toast.error(error.message || '文件上传失败');
        return { success: false, error: error.message };
      }
    });

    const results = await Promise.all(uploadPromises);
    const successfulUploads = results.filter(result => result.success);
    
    if (successfulUploads.length > 0) {
      toast.success(`成功上传 ${successfulUploads.length} 个文件`);
      
      // 重新加载素材列表以获取完整的数据结构
      console.log('上传完成，重新加载素材列表...');
      await loadMaterials(user.id);
    }
    
    const failedUploads = results.filter(result => !result.success);
    if (failedUploads.length > 0) {
      console.error('部分文件上传失败:', failedUploads);
    }

    setIsUploading(false);
  };

  // 删除素材
  const handleDeleteMaterial = async (materialId) => {
    if (!user?.id) {
      toast.error('请先登录');
      return;
    }

    try {
      const response = await materialLibraryAPI.deleteMaterial(user.id, materialId);
      if (response.success) {
        setMaterials(prev => prev.filter(material => material.id !== materialId));
        toast.success('删除成功');
      } else {
        toast.error(response.error || '删除失败');
      }
    } catch (error) {
      console.error('删除素材失败:', error);
      toast.error('删除失败');
    }
  };

  // 更新素材名称
  const handleUpdateMaterialName = async (materialId, newName) => {
    if (!user?.id) {
      toast.error('请先登录');
      return;
    }

    try {
      const response = await materialLibraryAPI.updateMaterial(user.id, materialId, {
        original_filename: newName
      });
      if (response.success) {
        setMaterials(prev => prev.map(material => 
          material.id === materialId 
            ? { ...material, name: newName }
            : material
        ));
        toast.success('更新成功');
      } else {
        toast.error(response.error || '更新失败');
      }
    } catch (error) {
      console.error('更新素材名称失败:', error);
      toast.error('更新失败');
    }
  };

  // 拖拽上传处理
  const handleDragOver = useCallback((e) => {
    e.preventDefault();
    e.stopPropagation();
  }, []);

  const handleDrop = useCallback((e) => {
    e.preventDefault();
    e.stopPropagation();
    
    const files = Array.from(e.dataTransfer.files);
    if (files.length > 0) {
      handleFileUpload(files);
    }
  }, []);

  const handleFileInput = (e) => {
    const files = Array.from(e.target.files);
    if (files.length > 0) {
      handleFileUpload(files);
    }
    // 重置input值
    if (fileInputRef.current) {
      fileInputRef.current.value = '';
    }
  };

  // 渲染上传区域
  const renderUploadArea = () => {
    const getUploadTitle = () => {
      switch (activeTab) {
        case 'face':
          return '人脸图片上传';
        case 'product':
          return '产品图片上传';
        case 'original':
          return '原始图片上传';
      }
    };

    return (
      <div className="mb-8">
        <div className="flex items-center gap-2 mb-4">
          <h3 className="text-lg font-semibold text-gray-900">{getUploadTitle()}</h3>
          <TooltipProvider>
            <Tooltip>
              <TooltipTrigger>
                <HelpCircle className="w-4 h-4 text-gray-400" />
              </TooltipTrigger>
              <TooltipContent>
                <p>支持PNG、JPG、JPEG格式，文件大小不超过200MB</p>
              </TooltipContent>
            </Tooltip>
          </TooltipProvider>
        </div>

        <div
          ref={dropZoneRef}
          className={`border-2 border-dashed rounded-lg p-8 text-center transition-colors ${
            isUploading 
              ? 'border-blue-300 bg-blue-50 cursor-not-allowed' 
              : 'border-gray-300 hover:border-gray-400 cursor-pointer'
          }`}
          onDragOver={handleDragOver}
          onDrop={handleDrop}
          onClick={() => !isUploading && fileInputRef.current?.click()}
        >
          <input
            ref={fileInputRef}
            type="file"
            multiple
            accept="image/png,image/jpg,image/jpeg"
            onChange={handleFileInput}
            className="hidden"
            disabled={isUploading}
          />
          
          <div className="flex flex-col items-center">
            {isUploading ? (
              <>
                <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mb-4"></div>
                <p className="text-lg font-medium text-blue-700 mb-2">正在上传...</p>
                <p className="text-sm text-blue-500">请稍候，文件正在处理中</p>
              </>
            ) : (
              <>
                <Upload className="w-12 h-12 text-gray-400 mb-4" />
                <p className="text-lg font-medium text-gray-700 mb-2">拖拽文件到这里</p>
                <p className="text-sm text-gray-500 mb-4">支持PNG, JPG, JPEG格式, 不超过200MB</p>
                <Button variant="outline" className="mt-2">
                  浏览文件
                </Button>
              </>
            )}
          </div>
        </div>
      </div>
    );
  };

  return (
    <div className="p-6 bg-white min-h-screen">
      <div className="max-w-6xl mx-auto">
        {/* 页面标题 */}
        <div className="mb-8">
          <h1 className="text-3xl font-bold text-gray-900 mb-2">素材管理</h1>
        </div>

        {/* 导航标签 */}
        <div className="flex gap-2 mb-8">
          <Button
            variant={activeTab === 'face' ? 'default' : 'outline'}
            onClick={() => setActiveTab('face')}
            className="flex items-center gap-2"
          >
            <PersonIcon />
            IP素材 (人脸)
          </Button>
          <Button
            variant={activeTab === 'product' ? 'default' : 'outline'}
            onClick={() => setActiveTab('product')}
            className="flex items-center gap-2"
          >
            <TShirtIcon />
            产品素材 (服装)
          </Button>
          <Button
            variant={activeTab === 'original' ? 'default' : 'outline'}
            onClick={() => setActiveTab('original')}
            className="flex items-center gap-2"
          >
            <UploadIcon />
            原始素材（原图）
          </Button>
        </div>

        {/* 上传区域 */}
        {renderUploadArea()}

        {/* 已上传素材 */}
        <div className="mb-6">
          <h3 className="text-lg font-semibold text-gray-900 mb-4">
            已上传素材({materials.length})
          </h3>
          
          {isLoading || isUploading ? (
            <div className="flex flex-col items-center justify-center py-12">
              <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900 mb-3"></div>
              <p className="text-sm text-gray-600">
                {isUploading ? '正在处理上传的文件...' : '加载素材中...'}
              </p>
            </div>
          ) : materials.length > 0 ? (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
              {materials.map((material) => (
                <MaterialCard 
                  key={material.id}
                  material={material}
                  onDelete={handleDeleteMaterial}
                  onUpdateName={handleUpdateMaterialName}
                />
              ))}
            </div>
          ) : (
            <Card>
              <CardContent className="p-12 text-center">
                <Upload className="w-12 h-12 text-gray-400 mx-auto mb-4" />
                <p className="text-gray-600">暂无素材</p>
                <p className="text-sm text-gray-500 mt-1">点击上传按钮开始添加素材</p>
              </CardContent>
            </Card>
          )}
        </div>
      </div>
    </div>
  );
} 