
import React, { useState, useEffect, useRef, useCallback } from 'react';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Card, CardContent, CardFooter } from '@/components/ui/card';
import { User, Upload, HelpCircle, Trash2, Loader2 } from 'lucide-react';
import BatchUploader from '../components/materials/BatchUploader';
import MaterialCard from '../components/materials/MaterialCard';
import { Separator } from '@/components/ui/separator';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
import { Input } from '@/components/ui/input';

const TShirtIcon = () => (
    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="lucide lucide-shirt"><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>
);

export default function MaterialManagement() {
    const [materials, setMaterials] = useState([]);
    const [uploadedImages, setUploadedImages] = useState([]);

    useEffect(() => {
        loadMaterials();
        loadUploadedImages();
    }, []);

    const loadMaterials = async () => {
        // 模拟数据加载
        const mockMaterials = [
            {
                id: '1',
                name: '时尚连衣裙',
                type: 'product',
                file_url: 'https://example.com/dress.jpg',
                created_date: '2024-01-15T10:00:00Z',
                matched_xiaohongshu_topics: ['时尚', '穿搭', '夏季']
            },
            {
                id: '2',
                name: '运动鞋',
                type: 'product',
                file_url: 'https://example.com/shoes.jpg',
                created_date: '2024-01-14T15:30:00Z',
                matched_xiaohongshu_topics: ['运动', '时尚', '舒适']
            },
            {
                id: '3',
                name: '模特IP',
                type: 'ip',
                file_url: 'https://example.com/model.jpg',
                created_date: '2024-01-13T09:20:00Z',
                matched_xiaohongshu_topics: ['模特', '时尚', '专业']
            }
        ];
        setMaterials(mockMaterials);
    };

    const loadUploadedImages = () => {
        try {
            const savedImages = JSON.parse(localStorage.getItem('uploadedImages') || '[]');
            const validImages = savedImages.filter(img => img.id && img.name && img.previewUrl);
            setUploadedImages(validImages);
        } catch (error) {
            console.error("Failed to load uploaded images:", error);
            setUploadedImages([]);
        }
    };

    const handleDelete = async (materialId) => {
        // 模拟删除操作
        setMaterials(prev => prev.filter(material => material.id !== materialId));
    };

    const handleUpdateName = async (materialId, updatedData) => {
        // 模拟更新操作
        setMaterials(prev => prev.map(material => 
            material.id === materialId 
                ? { ...material, ...updatedData }
                : material
        ));
    };

    const fileToBase64 = (file) => {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = () => resolve(reader.result);
            reader.onerror = error => reject(error);
        });
    };
    
    const handleImageUpload = async (files) => {
        const newImagesPromises = Array.from(files).map(async file => {
            try {
                const previewUrl = await fileToBase64(file);
                return {
                    id: `upload_${Date.now()}_${Math.random()}`,
                    name: file.name.split('.').slice(0, -1).join('.'),
                    previewUrl: previewUrl,
                };
            } catch (error) {
                console.error("Error converting file to Base64:", error);
                return null;
            }
        });

        const resolvedNewImages = (await Promise.all(newImagesPromises)).filter(Boolean);
        const updatedImages = [...uploadedImages, ...resolvedNewImages];
        setUploadedImages(updatedImages);
        
        try {
            localStorage.setItem('uploadedImages', JSON.stringify(updatedImages));
        } catch (error) {
            console.error("Failed to save images to localStorage:", error);
            alert("Error saving images: Storage limit reached or other issue. Images might not persist.");
        }
    };

    const handleRemoveUploadedImage = (imageId) => {
        setUploadedImages(prev => {
            const updatedImages = prev.filter(img => img.id !== imageId);
            
            try {
                localStorage.setItem('uploadedImages', JSON.stringify(updatedImages));
            } catch (error) {
                console.error("Failed to update localStorage:", error);
            }
            
            return updatedImages;
        });
    };

    const handleUpdateUploadedImageName = (imageId, newName) => {
        setUploadedImages(prev => {
            const updatedImages = prev.map(img => 
                img.id === imageId ? { ...img, name: newName } : img
            );
            
            try {
                localStorage.setItem('uploadedImages', JSON.stringify(updatedImages));
            } catch (error) {
                console.error("Failed to update localStorage:", error);
            }
            
            return updatedImages;
        });
    };

    const productMaterials = materials.filter(material => material.type === 'product');
    const ipMaterials = materials.filter(material => material.type === 'ip');

    return (
        <div className="p-6">
            <div className="max-w-7xl mx-auto">
                {/* 页面标题 */}
                <div className="mb-8">
                    <h1 className="text-3xl font-bold text-slate-900 mb-2">素材库管理</h1>
                    <p className="text-slate-600">管理产品素材和IP素材，支持批量上传和编辑</p>
                </div>

                {/* 统计信息 */}
                <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
                    <Card>
                        <CardContent className="p-4">
                            <div className="flex items-center justify-between">
                                <div>
                                    <p className="text-sm font-medium text-slate-600">总素材</p>
                                    <p className="text-2xl font-bold text-slate-900">{materials.length}</p>
                                </div>
                                <div className="w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center">
                                    <Upload className="w-5 h-5 text-blue-600" />
                                </div>
                            </div>
                        </CardContent>
                    </Card>

                    <Card>
                        <CardContent className="p-4">
                            <div className="flex items-center justify-between">
                                <div>
                                    <p className="text-sm font-medium text-slate-600">产品素材</p>
                                    <p className="text-2xl font-bold text-slate-900">{productMaterials.length}</p>
                                </div>
                                <div className="w-10 h-10 bg-green-100 rounded-lg flex items-center justify-center">
                                    <TShirtIcon className="w-5 h-5 text-green-600" />
                                </div>
                            </div>
                        </CardContent>
                    </Card>

                    <Card>
                        <CardContent className="p-4">
                            <div className="flex items-center justify-between">
                                <div>
                                    <p className="text-sm font-medium text-slate-600">IP素材</p>
                                    <p className="text-2xl font-bold text-slate-900">{ipMaterials.length}</p>
                                </div>
                                <div className="w-10 h-10 bg-purple-100 rounded-lg flex items-center justify-center">
                                    <User className="w-5 h-5 text-purple-600" />
                                </div>
                            </div>
                        </CardContent>
                    </Card>

                    <Card>
                        <CardContent className="p-4">
                            <div className="flex items-center justify-between">
                                <div>
                                    <p className="text-sm font-medium text-slate-600">待处理</p>
                                    <p className="text-2xl font-bold text-slate-900">{uploadedImages.length}</p>
                                </div>
                                <div className="w-10 h-10 bg-orange-100 rounded-lg flex items-center justify-center">
                                    <Loader2 className="w-5 h-5 text-orange-600" />
                                </div>
                            </div>
                        </CardContent>
                    </Card>
                </div>

                {/* 主要内容区域 */}
                <Tabs defaultValue="products" className="w-full">
                    <TabsList className="grid w-full grid-cols-3">
                        <TabsTrigger value="products">产品素材</TabsTrigger>
                        <TabsTrigger value="ips">IP素材</TabsTrigger>
                        <TabsTrigger value="upload">上传管理</TabsTrigger>
                    </TabsList>

                    <TabsContent value="products" className="mt-6">
                        <MaterialTabContent
                            type="product"
                            materials={productMaterials}
                            onDelete={handleDelete}
                            onUpdateName={handleUpdateName}
                            onUploadComplete={handleImageUpload}
                        />
                    </TabsContent>

                    <TabsContent value="ips" className="mt-6">
                        <MaterialTabContent
                            type="ip"
                            materials={ipMaterials}
                            onDelete={handleDelete}
                            onUpdateName={handleUpdateName}
                            onUploadComplete={handleImageUpload}
                        />
                    </TabsContent>

                    <TabsContent value="upload" className="mt-6">
                        <UploadImagesSection
                            uploadedImages={uploadedImages}
                            onImageUpload={handleImageUpload}
                            onRemoveImage={handleRemoveUploadedImage}
                            onUpdateImageName={handleUpdateUploadedImageName}
                        />
                    </TabsContent>
                </Tabs>
            </div>
        </div>
    );
}

function MaterialTabContent({ type, materials, onDelete, onUpdateName, onUploadComplete }) {
    const [isUploading, setIsUploading] = useState(false);

    const handleUploadComplete = async (files) => {
        setIsUploading(true);
        try {
            await onUploadComplete(files);
        } catch (error) {
            console.error('Upload failed:', error);
        } finally {
            setIsUploading(false);
        }
    };

    return (
        <div className="space-y-6">
            <div className="flex justify-between items-center">
                <h2 className="text-xl font-semibold text-slate-900">
                    {type === 'product' ? '产品素材' : 'IP素材'}
                </h2>
                <BatchUploader
                    title={`上传${type === 'product' ? '产品' : 'IP'}素材`}
                    description={`批量上传${type === 'product' ? '产品' : 'IP'}图片素材`}
                    materialType={type}
                    onUploadComplete={handleUploadComplete}
                />
            </div>

            <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={onDelete}
                        onUpdateName={onUpdateName}
                    />
                ))}
            </div>

            {materials.length === 0 && (
                <Card>
                    <CardContent className="p-12 text-center">
                        <Upload className="w-12 h-12 text-slate-400 mx-auto mb-4" />
                        <p className="text-slate-600">暂无{type === 'product' ? '产品' : 'IP'}素材</p>
                        <p className="text-sm text-slate-500 mt-1">点击上传按钮开始添加素材</p>
                    </CardContent>
                </Card>
            )}
        </div>
    );
}

function UploadImagesSection({ uploadedImages, onImageUpload, onRemoveImage, onUpdateImageName }) {
    const fileInputRef = useRef(null);

    const handleFileInput = (e) => {
        const files = Array.from(e.target.files);
        if (files.length > 0) {
            onImageUpload(files);
        }
        // 重置input值，允许重复选择相同文件
        if (fileInputRef.current) {
            fileInputRef.current.value = '';
        }
    };

    return (
        <div className="space-y-6">
            <div className="flex justify-between items-center">
                <h2 className="text-xl font-semibold text-slate-900">上传管理</h2>
                <div className="flex gap-2">
                    <input
                        ref={fileInputRef}
                        type="file"
                        multiple
                        accept="image/*"
                        onChange={handleFileInput}
                        className="hidden"
                    />
                    <Button onClick={() => fileInputRef.current?.click()}>
                        <Upload className="w-4 h-4 mr-2" />
                        选择图片
                    </Button>
                </div>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
                {uploadedImages.map((image) => (
                    <UploadedImageCard
                        key={image.id}
                        image={image}
                        onRemove={onRemoveImage}
                        onUpdateName={onUpdateImageName}
                    />
                ))}
            </div>

            {uploadedImages.length === 0 && (
                <Card>
                    <CardContent className="p-12 text-center">
                        <Upload className="w-12 h-12 text-slate-400 mx-auto mb-4" />
                        <p className="text-slate-600">暂无待处理图片</p>
                        <p className="text-sm text-slate-500 mt-1">点击选择图片按钮开始上传</p>
                    </CardContent>
                </Card>
            )}
        </div>
    );
}

function UploadedImageCard({ image, onRemove, onUpdateName }) {
    const [isEditing, setIsEditing] = useState(false);
    const [editName, setEditName] = useState(image.name);

    const handleNameChange = (e) => {
        setEditName(e.target.value);
    };

    const handleSaveName = async () => {
        if (editName.trim() !== image.name) {
            await onUpdateName(image.id, editName.trim());
        }
        setIsEditing(false);
    };

    return (
        <Card className="overflow-hidden">
            <div className="aspect-square bg-slate-100 relative group">
                <img
                    src={image.previewUrl}
                    alt={image.name}
                    className="w-full h-full object-cover"
                />
                <div className="absolute inset-0 bg-black/50 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center">
                    <Button
                        variant="destructive"
                        size="sm"
                        onClick={() => onRemove(image.id)}
                    >
                        <Trash2 className="w-4 h-4" />
                    </Button>
                </div>
            </div>
            <CardFooter className="p-3">
                <div className="w-full">
                    {isEditing ? (
                        <div className="flex gap-2">
                            <Input
                                value={editName}
                                onChange={handleNameChange}
                                className="flex-1"
                                autoFocus
                            />
                            <Button size="sm" onClick={handleSaveName}>
                                保存
                            </Button>
                            <Button size="sm" variant="outline" onClick={() => setIsEditing(false)}>
                                取消
                            </Button>
                        </div>
                    ) : (
                        <div className="flex items-center justify-between">
                            <span className="text-sm font-medium truncate">{image.name}</span>
                            <Button size="sm" variant="outline" onClick={() => setIsEditing(true)}>
                                编辑
                            </Button>
                        </div>
                    )}
                </div>
            </CardFooter>
        </Card>
    );
}
