import React, { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Badge } from '@/components/ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import {
    Search,
    Filter,
    Video,
    Image as ImageIcon,
    Tag,
    ShoppingCart,
    Layers,
    Eye,
    Download,
    RefreshCw
} from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';

export default function AIAssetSearch() {
    const [assets, setAssets] = useState([]);
    const [filteredAssets, setFilteredAssets] = useState([]);
    const [loading, setLoading] = useState(false);
    
    // 搜索和筛选状态
    const [searchTerm, setSearchTerm] = useState('');
    const [selectedCategory, setSelectedCategory] = useState('all');
    const [selectedAIType, setSelectedAIType] = useState('all');
    const [activeTab, setActiveTab] = useState('all');

    useEffect(() => {
        loadAssets();
    }, []);

    useEffect(() => {
        filterAssets();
    }, [assets, searchTerm, selectedCategory, selectedAIType, activeTab]);

    const loadAssets = async () => {
        setLoading(true);
        try {
            // 模拟数据加载
            const mockAssets = [
                {
                    id: '1',
                    sku: 'SKU001',
                    product_name: '时尚连衣裙',
                    product_category: '女装',
                    tmall_product_id: 'TM001',
                    matched_tmall_keywords: ['连衣裙', '时尚', '夏季'],
                    matched_xiaohongshu_topics: ['穿搭', '时尚', '夏季穿搭'],
                    ai_videos: [
                        {
                            id: 'v1',
                            type: 'product_showcase',
                            url: 'https://example.com/video1.mp4',
                            thumbnail: 'https://example.com/thumb1.jpg',
                            duration: '00:30',
                            status: 'completed'
                        }
                    ],
                    ai_images: [
                        {
                            id: 'i1',
                            type: 'product_photo',
                            url: 'https://example.com/image1.jpg',
                            status: 'completed'
                        }
                    ]
                },
                {
                    id: '2',
                    sku: 'SKU002',
                    product_name: '运动鞋',
                    product_category: '鞋靴',
                    tmall_product_id: 'TM002',
                    matched_tmall_keywords: ['运动鞋', '舒适', '时尚'],
                    matched_xiaohongshu_topics: ['运动', '时尚', '舒适'],
                    ai_videos: [
                        {
                            id: 'v2',
                            type: 'lifestyle',
                            url: 'https://example.com/video2.mp4',
                            thumbnail: 'https://example.com/thumb2.jpg',
                            duration: '00:45',
                            status: 'processing'
                        }
                    ],
                    ai_images: [
                        {
                            id: 'i2',
                            type: 'lifestyle',
                            url: 'https://example.com/image2.jpg',
                            status: 'completed'
                        }
                    ]
                }
            ];
            setAssets(mockAssets);
        } catch (error) {
            console.error('加载AI素材失败:', error);
        }
        setLoading(false);
    };

    const filterAssets = () => {
        let filtered = assets;

        // 文本搜索
        if (searchTerm.trim()) {
            const searchLower = searchTerm.toLowerCase();
            filtered = filtered.filter(asset => 
                asset.sku?.toLowerCase().includes(searchLower) ||
                asset.product_name?.toLowerCase().includes(searchLower) ||
                asset.product_category?.toLowerCase().includes(searchLower) ||
                asset.tmall_product_id?.toLowerCase().includes(searchLower) ||
                asset.matched_tmall_keywords?.some(keyword => keyword.toLowerCase().includes(searchLower)) ||
                asset.matched_xiaohongshu_topics?.some(topic => topic.toLowerCase().includes(searchLower))
            );
        }

        // 商品分类筛选
        if (selectedCategory !== 'all') {
            filtered = filtered.filter(asset => asset.product_category === selectedCategory);
        }

        // AI类型筛选
        if (selectedAIType !== 'all') {
            filtered = filtered.filter(asset => {
                const hasVideoType = asset.ai_videos?.some(video => video.type === selectedAIType);
                const hasImageType = asset.ai_images?.some(image => image.type === selectedAIType);
                return hasVideoType || hasImageType;
            });
        }

        // 标签页筛选
        if (activeTab !== 'all') {
            if (activeTab === 'videos') {
                filtered = filtered.filter(asset => asset.ai_videos && asset.ai_videos.length > 0);
            } else if (activeTab === 'images') {
                filtered = filtered.filter(asset => asset.ai_images && asset.ai_images.length > 0);
            }
        }

        setFilteredAssets(filtered);
    };

    const handleSearch = () => {
        filterAssets();
    };

    const getAITypeLabel = (type) => {
        const labels = {
            'product_showcase': '产品展示',
            'lifestyle': '生活方式',
            'product_photo': '产品照片',
            'model_photo': '模特照片',
            'scene_photo': '场景照片'
        };
        return labels[type] || type;
    };

    const getStatusColor = (status) => {
        const colors = {
            'completed': 'bg-green-100 text-green-700',
            'processing': 'bg-yellow-100 text-yellow-700',
            'failed': 'bg-red-100 text-red-700',
            'pending': 'bg-gray-100 text-gray-700'
        };
        return colors[status] || 'bg-gray-100 text-gray-700';
    };

    const getStatusLabel = (status) => {
        const labels = {
            'completed': '已完成',
            'processing': '处理中',
            'failed': '失败',
            'pending': '等待中'
        };
        return labels[status] || status;
    };

    const categories = [
        { value: 'all', label: '全部分类' },
        { value: '女装', label: '女装' },
        { value: '男装', label: '男装' },
        { value: '鞋靴', label: '鞋靴' },
        { value: '配饰', label: '配饰' },
        { value: '美妆', label: '美妆' }
    ];

    const aiTypes = [
        { value: 'all', label: '全部类型' },
        { value: 'product_showcase', label: '产品展示' },
        { value: 'lifestyle', label: '生活方式' },
        { value: 'product_photo', label: '产品照片' },
        { value: 'model_photo', label: '模特照片' },
        { value: 'scene_photo', label: '场景照片' }
    ];

    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">搜索和管理AI生成的素材内容</p>
                </div>

                {/* 搜索和筛选工具栏 */}
                <div className="bg-white rounded-xl shadow-sm border border-slate-200 p-6 mb-6">
                    <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
                        {/* 搜索框 */}
                        <div className="md:col-span-2">
                            <div className="relative">
                                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-slate-400 w-4 h-4" />
                                <Input
                                    placeholder="搜索商品名称、SKU、分类..."
                                    value={searchTerm}
                                    onChange={(e) => setSearchTerm(e.target.value)}
                                    className="pl-10"
                                />
                            </div>
                        </div>

                        {/* 分类筛选 */}
                        <div>
                            <Select value={selectedCategory} onValueChange={setSelectedCategory}>
                                <SelectTrigger>
                                    <SelectValue />
                                </SelectTrigger>
                                <SelectContent>
                                    {categories.map(category => (
                                        <SelectItem key={category.value} value={category.value}>
                                            {category.label}
                                        </SelectItem>
                                    ))}
                                </SelectContent>
                            </Select>
                        </div>

                        {/* AI类型筛选 */}
                        <div>
                            <Select value={selectedAIType} onValueChange={setSelectedAIType}>
                                <SelectTrigger>
                                    <SelectValue />
                                </SelectTrigger>
                                <SelectContent>
                                    {aiTypes.map(type => (
                                        <SelectItem key={type.value} value={type.value}>
                                            {type.label}
                                        </SelectItem>
                                    ))}
                                </SelectContent>
                            </Select>
                        </div>
                    </div>

                    {/* 标签页 */}
                    <div className="mt-6">
                        <Tabs value={activeTab} onValueChange={setActiveTab}>
                            <TabsList className="grid w-full grid-cols-4">
                                <TabsTrigger value="all">全部</TabsTrigger>
                                <TabsTrigger value="videos">视频</TabsTrigger>
                                <TabsTrigger value="images">图片</TabsTrigger>
                                <TabsTrigger value="processing">处理中</TabsTrigger>
                            </TabsList>
                        </Tabs>
                    </div>
                </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">{assets.length}</p>
                                </div>
                                <div className="w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center">
                                    <Layers 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">
                                        {assets.filter(asset => asset.ai_videos?.length > 0).length}
                                    </p>
                                </div>
                                <div className="w-10 h-10 bg-green-100 rounded-lg flex items-center justify-center">
                                    <Video 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">图片素材</p>
                                    <p className="text-2xl font-bold text-slate-900">
                                        {assets.filter(asset => asset.ai_images?.length > 0).length}
                                    </p>
                                </div>
                                <div className="w-10 h-10 bg-purple-100 rounded-lg flex items-center justify-center">
                                    <ImageIcon 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">
                                        {assets.filter(asset => 
                                            asset.ai_videos?.some(v => v.status === 'processing') ||
                                            asset.ai_images?.some(i => i.status === 'processing')
                                        ).length}
                                    </p>
                                </div>
                                <div className="w-10 h-10 bg-yellow-100 rounded-lg flex items-center justify-center">
                                    <RefreshCw className="w-5 h-5 text-yellow-600" />
                                </div>
                            </div>
                        </CardContent>
                    </Card>
                </div>

                {/* 素材列表 */}
                <div className="grid gap-6">
                    {loading ? (
                        <div className="text-center py-12">
                            <RefreshCw className="w-8 h-8 animate-spin text-blue-600 mx-auto mb-4" />
                            <p className="text-slate-600">加载中...</p>
                        </div>
                    ) : (
                        <AnimatePresence>
                            {filteredAssets.map((asset) => (
                                <motion.div
                                    key={asset.id}
                                    initial={{ opacity: 0, y: 20 }}
                                    animate={{ opacity: 1, y: 0 }}
                                    exit={{ opacity: 0, y: -20 }}
                                    transition={{ duration: 0.3 }}
                                >
                                    <AIAssetCard asset={asset} />
                                </motion.div>
                            ))}
                        </AnimatePresence>
                    )}

                    {!loading && filteredAssets.length === 0 && (
                        <Card>
                            <CardContent className="p-12 text-center">
                                <Search 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>
            </div>
        </div>
    );
}

function AIAssetCard({ asset }) {
    const [expanded, setExpanded] = useState(false);

    const getAITypeLabel = (type) => {
        const labels = {
            'product_showcase': '产品展示',
            'lifestyle': '生活方式',
            'product_photo': '产品照片',
            'model_photo': '模特照片',
            'scene_photo': '场景照片'
        };
        return labels[type] || type;
    };

    const getStatusColor = (status) => {
        const colors = {
            'completed': 'bg-green-100 text-green-700',
            'processing': 'bg-yellow-100 text-yellow-700',
            'failed': 'bg-red-100 text-red-700',
            'pending': 'bg-gray-100 text-gray-700'
        };
        return colors[status] || 'bg-gray-100 text-gray-700';
    };

    const getStatusLabel = (status) => {
        const labels = {
            'completed': '已完成',
            'processing': '处理中',
            'failed': '失败',
            'pending': '等待中'
        };
        return labels[status] || status;
    };

    return (
        <Card>
            <CardHeader>
                <div className="flex items-center justify-between">
                    <div className="flex items-center gap-3">
                        <div className="w-10 h-10 bg-gradient-to-br from-blue-500 to-purple-500 rounded-lg flex items-center justify-center">
                            <ShoppingCart className="w-5 h-5 text-white" />
                        </div>
                        <div>
                            <CardTitle className="text-lg">{asset.product_name}</CardTitle>
                            <p className="text-sm text-slate-500">SKU: {asset.sku}</p>
                        </div>
                    </div>
                    
                    <div className="flex items-center gap-2">
                        <Badge variant="outline">{asset.product_category}</Badge>
                        <Button
                            variant="outline"
                            size="sm"
                            onClick={() => setExpanded(!expanded)}
                        >
                            {expanded ? '收起' : '展开'}
                        </Button>
                    </div>
                </div>
            </CardHeader>
            
            <CardContent>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    {/* 视频素材 */}
                    {asset.ai_videos && asset.ai_videos.length > 0 && (
                        <div>
                            <h4 className="font-medium text-slate-900 mb-3 flex items-center gap-2">
                                <Video className="w-4 h-4" />
                                视频素材 ({asset.ai_videos.length})
                            </h4>
                            <div className="space-y-3">
                                {asset.ai_videos.map(video => (
                                    <div key={video.id} className="border rounded-lg p-3">
                                        <div className="flex items-center justify-between mb-2">
                                            <span className="text-sm font-medium">{getAITypeLabel(video.type)}</span>
                                            <Badge className={getStatusColor(video.status)}>
                                                {getStatusLabel(video.status)}
                                            </Badge>
                                        </div>
                                        <div className="aspect-video bg-slate-100 rounded-lg mb-2"></div>
                                        <div className="flex items-center justify-between text-sm text-slate-600">
                                            <span>时长: {video.duration}</span>
                                            <div className="flex gap-2">
                                                <Button size="sm" variant="outline">
                                                    <Eye className="w-3 h-3" />
                                                </Button>
                                                <Button size="sm" variant="outline">
                                                    <Download className="w-3 h-3" />
                                                </Button>
                                            </div>
                                        </div>
                                    </div>
                                ))}
                            </div>
                        </div>
                    )}

                    {/* 图片素材 */}
                    {asset.ai_images && asset.ai_images.length > 0 && (
                        <div>
                            <h4 className="font-medium text-slate-900 mb-3 flex items-center gap-2">
                                <ImageIcon className="w-4 h-4" />
                                图片素材 ({asset.ai_images.length})
                            </h4>
                            <div className="space-y-3">
                                {asset.ai_images.map(image => (
                                    <div key={image.id} className="border rounded-lg p-3">
                                        <div className="flex items-center justify-between mb-2">
                                            <span className="text-sm font-medium">{getAITypeLabel(image.type)}</span>
                                            <Badge className={getStatusColor(image.status)}>
                                                {getStatusLabel(image.status)}
                                            </Badge>
                                        </div>
                                        <div className="aspect-square bg-slate-100 rounded-lg mb-2"></div>
                                        <div className="flex items-center justify-between">
                                            <span className="text-sm text-slate-600">图片素材</span>
                                            <div className="flex gap-2">
                                                <Button size="sm" variant="outline">
                                                    <Eye className="w-3 h-3" />
                                                </Button>
                                                <Button size="sm" variant="outline">
                                                    <Download className="w-3 h-3" />
                                                </Button>
                                            </div>
                                        </div>
                                    </div>
                                ))}
                            </div>
                        </div>
                    )}
                </div>

                {/* 关键词标签 */}
                {expanded && (
                    <div className="mt-6 pt-6 border-t">
                        <h4 className="font-medium text-slate-900 mb-3 flex items-center gap-2">
                            <Tag className="w-4 h-4" />
                            关键词标签
                        </h4>
                        <div className="space-y-3">
                            <div>
                                <p className="text-sm font-medium text-slate-600 mb-2">天猫关键词</p>
                                <div className="flex flex-wrap gap-2">
                                    {asset.matched_tmall_keywords?.map((keyword, index) => (
                                        <Badge key={index} variant="secondary">
                                            {keyword}
                                        </Badge>
                                    ))}
                                </div>
                            </div>
                            <div>
                                <p className="text-sm font-medium text-slate-600 mb-2">小红书话题</p>
                                <div className="flex flex-wrap gap-2">
                                    {asset.matched_xiaohongshu_topics?.map((topic, index) => (
                                        <Badge key={index} variant="secondary">
                                            {topic}
                                        </Badge>
                                    ))}
                                </div>
                            </div>
                        </div>
                    </div>
                )}
            </CardContent>
        </Card>
    );
}