import React, { useRef, useState } from 'react';
import { Upload, ImageIcon, Heart, Trash2, Play, Video } from 'lucide-react';
import { cn } from '@/utils';
import { ViewDisplayControl, ViewMode } from './ViewDisplayControl';
import { CreateItemControl } from './CreateItemControl';
import { SecureImage } from './SecureImage';
import { GenerationRecord } from '@/types';
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Button } from "@/components/ui/button";
import { useConfirm } from '@/components/ui/confirm-dialog';

export interface MediaManagerProps {
    // Identity
    containerId: string;
    
    // State
    activeTab: 'image' | 'video';
    onTabChange: (tab: 'image' | 'video') => void;
    viewMode: ViewMode;
    onViewModeChange: (mode: ViewMode) => void;
    gridCols: number;
    setGridCols: (cols: number) => void;
    listCols: number;
    setListCols: (cols: number) => void;
    
    // View Config
    showList?: boolean;
    gridMax?: number;
    className?: string;
    hideTabs?: boolean;
    scrollable?: boolean;

    // Data
    imageUrls?: string[]; // Available images
    videoUrls?: string[]; // Available videos
    generations?: GenerationRecord[]; // Full history
    currentCoverUrl?: string; // The URL of the current cover image

    // Actions - General
    onPreview: (media: { url: string; type: 'image' | 'video'; generation?: GenerationRecord }) => void;
    
    // Actions - Image
    onUploadImage?: (id: string, file: File) => void;
    onSetCover?: (id: string, url: string) => void;
    onDeleteImage?: (id: string, url: string) => void;
    onCollectImage?: (id: string, url: string) => void; // From History to Available
    onUncollectImage?: (id: string, url: string) => void; // From Available to History

    // Actions - Video
    onUploadVideo?: (id: string, file: File) => void;
    onDeleteVideo?: (id: string, url: string) => void;
    onCollectVideo?: (id: string, url: string) => void;
    onUncollectVideo?: (id: string, url: string) => void;

    // Customization
    renderImageBadge?: (url: string, index: number, generation?: GenerationRecord) => React.ReactNode;
}

export function MediaManager({
    containerId,
    activeTab,
    onTabChange,
    viewMode,
    onViewModeChange,
    gridCols,
    setGridCols,
    listCols,
    setListCols,
    showList = true,
    gridMax = 6,
    className,
    hideTabs = false,
    scrollable = true,
    imageUrls = [],
    videoUrls = [],
    generations = [],
    currentCoverUrl,
    onPreview,
    onUploadImage,
    onSetCover,
    onDeleteImage,
    onCollectImage,
    onUncollectImage,
    onUploadVideo,
    onDeleteVideo,
    onCollectVideo,
    onUncollectVideo,
    renderImageBadge
}: MediaManagerProps) {
    const fileInputRef = useRef<HTMLInputElement>(null);
    const currentModalCols = viewMode === 'grid' ? gridCols : listCols;
    const { confirm, ConfirmDialog } = useConfirm();

    // Calculate History Items
    const historyImages = React.useMemo(() => {
        return activeTab === 'image' 
            ? generations
                .filter(g => g.type === 'image' && g.status === 'success')
                .flatMap(g => {
                    const urls = g.resultUrls || (g.resultUrl ? [g.resultUrl] : []);
                    return urls.map(url => ({ url, generation: g }));
                })
                .filter(item => !imageUrls.includes(item.url))
            : [];
    }, [activeTab, generations, imageUrls]);

    const historyVideos = React.useMemo(() => {
        return activeTab === 'video'
            ? generations
                .filter(g => g.type === 'video' && g.status === 'success' && g.resultUrl && !videoUrls.includes(g.resultUrl))
                .map(g => ({ url: g.resultUrl!, generation: g }))
            : [];
    }, [activeTab, generations, videoUrls]);

    const handleUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
        const file = e.target.files?.[0];
        if (file && containerId) {
            if (activeTab === 'image') {
                onUploadImage?.(containerId, file);
            } else {
                onUploadVideo?.(containerId, file);
            }
        }
        // Reset input
        e.target.value = '';
    };

    const ContentWrapper = scrollable ? ScrollArea : 'div';
    const wrapperClass = scrollable ? "flex-1 p-6" : "p-6";

    return (
        <>
        <ConfirmDialog />
        <div className={cn("flex flex-col h-full bg-background", className)}>
            {/* Header / Controls */}
            <div className="flex items-center justify-between px-6 py-4 border-b border-border">
                {hideTabs ? <div /> : (
                    <Tabs value={activeTab} onValueChange={(val) => onTabChange(val as 'image' | 'video')} className="w-fit">
                        <TabsList className="bg-muted p-1 h-auto rounded-lg">
                            <TabsTrigger value="image" className="gap-2 px-4 py-2 h-auto rounded-md data-[state=active]:bg-card data-[state=active]:text-foreground data-[state=active]:shadow-sm">
                                <ImageIcon size={16} />
                                <span>图片素材</span>
                            </TabsTrigger>
                            <TabsTrigger value="video" className="gap-2 px-4 py-2 h-auto rounded-md data-[state=active]:bg-card data-[state=active]:text-foreground data-[state=active]:shadow-sm">
                                <Video size={16} />
                                <span>视频素材</span>
                            </TabsTrigger>
                        </TabsList>
                    </Tabs>
                )}

                <div className="flex items-center gap-3">
                    <CreateItemControl 
                        label={activeTab === 'image' ? '上传图片' : '上传视频'}
                        icon={<Upload size={16} />}
                        onClick={() => fileInputRef.current?.click()}
                    />
                    <input 
                        ref={fileInputRef}
                        type="file" 
                        className="hidden" 
                        accept={activeTab === 'image' ? "image/*" : "video/*"}
                        onChange={handleUpload}
                    />
                    <ViewDisplayControl 
                        mode={viewMode}
                        onModeChange={onViewModeChange}
                        gridColumns={gridCols}
                        setGridColumns={setGridCols}
                        listColumns={listCols}
                        setListColumns={setListCols}
                        gridMax={gridMax}
                        showList={showList}
                    />
                </div>
            </div>

            {/* Content Area */}
            <ContentWrapper className={wrapperClass}>
                {activeTab === 'image' ? (
                    <div className="space-y-8 pb-6">
                        {/* Available Images */}
                        <div>
                            <h4 className="text-foreground font-medium mb-4 flex items-center gap-2">
                                    <div className="w-1 h-4 bg-blue-500 rounded-full" />
                                    可用图片 ({imageUrls.length || 0})
                            </h4>
                            <div className={cn(
                                "grid gap-4",
                                viewMode === 'grid' && currentModalCols === 2 && "grid-cols-2",
                                viewMode === 'grid' && currentModalCols === 3 && "grid-cols-3",
                                viewMode === 'grid' && currentModalCols === 4 && "grid-cols-4",
                                viewMode === 'grid' && currentModalCols === 5 && "grid-cols-5",
                                viewMode === 'grid' && currentModalCols === 6 && "grid-cols-6",
                                viewMode === 'grid' && currentModalCols === 7 && "grid-cols-7",
                                viewMode === 'grid' && currentModalCols === 8 && "grid-cols-8",
                                viewMode === 'list' && currentModalCols === 1 && "grid-cols-1",
                                viewMode === 'list' && currentModalCols === 2 && "grid-cols-2"
                            )}>
                                {imageUrls.map((url, index) => {
                                    const generation = generations?.find(g => (g.resultUrls || [g.resultUrl]).includes(url));
                                    
                                    return (
                                    <div 
                                        key={`available-${index}`}
                                        className="group relative aspect-square bg-background rounded-lg border border-border overflow-hidden hover:border-blue-500 transition-all cursor-pointer"
                                        onClick={() => {
                                            onPreview({ url, type: 'image', generation });
                                        }}
                                    >
                                        <SecureImage src={url} alt={`Version ${index + 1}`} className="w-full h-full object-cover object-top" />
                                        <div className="absolute top-2 left-2 bg-black/60 backdrop-blur-sm px-2 py-1 rounded text-[10px] text-white font-mono">
                                            {renderImageBadge ? renderImageBadge(url, index, generation) : `v${index + 1}`}
                                        </div>
                                        <div className="absolute top-2 right-2 flex gap-1 opacity-0 group-hover:opacity-100 transition-all">
                                            {currentCoverUrl === url ? (
                                                <div className="p-1.5 rounded bg-blue-500 text-white backdrop-blur-sm cursor-default" title="当前封面">
                                                    <ImageIcon size={14} />
                                                </div>
                                            ) : (
                                                <Button 
                                                    variant="ghost"
                                                    size="icon"
                                                    onClick={(e) => {
                                                        e.stopPropagation();
                                                        onSetCover?.(containerId, url);
                                                    }}
                                                    className="h-7 w-7 rounded bg-black/60 hover:bg-blue-500 text-white backdrop-blur-sm transition-colors border-none"
                                                    title="设为封面"
                                                >
                                                    <ImageIcon size={14} />
                                                </Button>
                                            )}
                                            <Button 
                                                variant="ghost"
                                                size="icon"
                                                onClick={(e) => {
                                                    e.stopPropagation();
                                                    onUncollectImage?.(containerId, url);
                                                }}
                                                className="h-7 w-7 rounded bg-black/60 hover:bg-white/20 text-red-500 backdrop-blur-sm transition-colors border-none"
                                                title="取消收藏 (移入历史)"
                                            >
                                                <Heart size={14} className="fill-current" />
                                            </Button>
                                            <Button 
                                                variant="ghost"
                                                size="icon"
                                                onClick={(e) => {
                                                    e.stopPropagation();
                                                    confirm({
                                                        title: '确认删除？',
                                                        description: '确定要删除这张图片吗？此操作无法撤销。',
                                                        variant: 'destructive',
                                                        onConfirm: () => onDeleteImage?.(containerId, url)
                                                    });
                                                }}
                                                className="h-7 w-7 rounded bg-black/60 hover:bg-white/20 text-red-500 backdrop-blur-sm transition-colors border-none"
                                                title="删除"
                                            >
                                                <Trash2 size={14} />
                                            </Button>
                                        </div>
                                        {currentCoverUrl === url && (
                                            <div className="absolute inset-0 border-2 border-blue-500 rounded-lg pointer-events-none" />
                                        )}
                                    </div>
                                ); })}
                            </div>
                        </div>

                        {/* History Images */}
                        {historyImages.length > 0 && (
                            <div>
                                <h4 className="text-foreground font-medium mb-4 flex items-center gap-2">
                                    <div className="w-1 h-4 bg-muted rounded-full" />
                                    生成历史 ({historyImages.length})
                                </h4>
                                <div className={cn(
                                    "grid gap-4",
                                    viewMode === 'grid' && currentModalCols === 2 && "grid-cols-2",
                                    viewMode === 'grid' && currentModalCols === 3 && "grid-cols-3",
                                    viewMode === 'grid' && currentModalCols === 4 && "grid-cols-4",
                                    viewMode === 'grid' && currentModalCols === 5 && "grid-cols-5",
                                    viewMode === 'grid' && currentModalCols === 6 && "grid-cols-6",
                                    viewMode === 'grid' && currentModalCols === 7 && "grid-cols-7",
                                    viewMode === 'grid' && currentModalCols === 8 && "grid-cols-8",
                                    viewMode === 'list' && currentModalCols === 1 && "grid-cols-1",
                                    viewMode === 'list' && currentModalCols === 2 && "grid-cols-2"
                                )}>
                                    {historyImages.map((item, index) => (
                                        <div 
                                            key={`${item.generation.id}-${index}`}
                                            className="group relative aspect-square bg-background rounded-lg border border-border overflow-hidden hover:border-blue-500 transition-all cursor-pointer"
                                            onClick={() => onPreview({ url: item.url, type: 'image', generation: item.generation })}
                                        >
                                            <SecureImage src={item.url} alt="Generated" className="w-full h-full object-cover opacity-60 group-hover:opacity-100 transition-opacity" />
                                            <div className="absolute top-2 left-2 bg-black/60 backdrop-blur-sm px-2 py-1 rounded text-[10px] text-white/60 font-mono">
                                                {new Date(item.generation.timestamp).toLocaleTimeString()}
                                            </div>
                                            <div className="absolute top-2 right-2 flex gap-1 opacity-0 group-hover:opacity-100 transition-all">
                                                <Button 
                                                    variant="ghost"
                                                    size="icon"
                                                    onClick={(e) => {
                                                        e.stopPropagation();
                                                        onCollectImage?.(containerId, item.url);
                                                    }}
                                                    className="h-7 w-7 rounded bg-black/60 hover:bg-blue-500 text-white backdrop-blur-sm transition-colors border-none"
                                                    title="收藏 (移入可用)"
                                                >
                                                    <Heart size={14} />
                                                </Button>
                                            </div>
                                            <div className="absolute bottom-0 inset-x-0 p-2 bg-gradient-to-t from-black/80 to-transparent">
                                                <p className="text-[10px] text-foreground/80 line-clamp-2">
                                                    {item.generation.prompt}
                                                </p>
                                            </div>
                                        </div>
                                    ))}
                                </div>
                            </div>
                        )}
                    </div>
                ) : (
                    <div className="space-y-8 pb-6">
                        {/* Available Videos */}
                        <div>
                            <h4 className="text-foreground font-medium mb-4 flex items-center gap-2">
                                <div className="w-1 h-4 bg-blue-500 rounded-full" />
                                可用视频 ({videoUrls.length || 0})
                            </h4>
                            <div className={cn(
                                "grid gap-4",
                                viewMode === 'grid' && currentModalCols === 2 && "grid-cols-2",
                                viewMode === 'grid' && currentModalCols === 3 && "grid-cols-3",
                                viewMode === 'grid' && currentModalCols === 4 && "grid-cols-4",
                                viewMode === 'grid' && currentModalCols === 5 && "grid-cols-5",
                                viewMode === 'grid' && currentModalCols === 6 && "grid-cols-6",
                                viewMode === 'grid' && currentModalCols === 7 && "grid-cols-7",
                                viewMode === 'grid' && currentModalCols === 8 && "grid-cols-8",
                                viewMode === 'list' && currentModalCols === 1 && "grid-cols-1",
                                viewMode === 'list' && currentModalCols === 2 && "grid-cols-2"
                            )}>
                                {videoUrls.map((url, index) => {
                                    const generation = generations?.find(g => g.resultUrl === url);
                                    return (
                                    <div 
                                        key={`available-video-${index}`}
                                        className="group relative aspect-video bg-background rounded-lg border border-border overflow-hidden hover:border-blue-500 transition-all cursor-pointer"
                                        onClick={() => {
                                            onPreview({ url, type: 'video', generation });
                                        }}
                                    >
                                        <video src={url} className="w-full h-full object-cover pointer-events-none" />
                                        <div className="absolute inset-0 flex items-center justify-center bg-black/20 group-hover:bg-black/40 transition-colors pointer-events-none">
                                            <div className="w-10 h-10 rounded-full bg-white/20 backdrop-blur-sm flex items-center justify-center group-hover:scale-110 transition-transform">
                                                <Play size={20} className="fill-white text-foreground ml-1" />
                                            </div>
                                        </div>
                                        <div className="absolute top-2 right-2 flex gap-1 opacity-0 group-hover:opacity-100 transition-all z-10">
                                            <Button 
                                                variant="ghost"
                                                size="icon"
                                                onClick={(e) => {
                                                    e.stopPropagation();
                                                    onUncollectVideo?.(containerId, url);
                                                }}
                                                className="w-7 h-7 p-0 rounded bg-black/60 hover:bg-white/20 text-red-500 backdrop-blur-sm transition-colors border-none"
                                                title="取消收藏 (移入历史)"
                                            >
                                                <Heart size={14} className="fill-current" />
                                            </Button>
                                            <Button 
                                                variant="ghost"
                                                size="icon"
                                                onClick={(e) => {
                                                    e.stopPropagation();
                                                    confirm({
                                                        title: '确认删除？',
                                                        description: '确定要删除这个视频吗？此操作无法撤销。',
                                                        variant: 'destructive',
                                                        onConfirm: () => onDeleteVideo?.(containerId, url)
                                                    });
                                                }}
                                                className="w-7 h-7 p-0 rounded bg-black/60 hover:bg-white/20 text-red-500 backdrop-blur-sm transition-colors border-none"
                                                title="删除"
                                            >
                                                <Trash2 size={14} />
                                            </Button>
                                        </div>
                                    </div>
                                );})}
                            </div>
                        </div>

                        {/* History Videos */}
                        {historyVideos.length > 0 && (
                            <div>
                                <h4 className="text-foreground font-medium mb-4 flex items-center gap-2">
                                    <div className="w-1 h-4 bg-muted rounded-full" />
                                    生成历史 ({historyVideos.length})
                                </h4>
                                <div className={cn(
                                    "grid gap-4",
                                    viewMode === 'grid' && currentModalCols === 2 && "grid-cols-2",
                                    viewMode === 'grid' && currentModalCols === 3 && "grid-cols-3",
                                    viewMode === 'grid' && currentModalCols === 4 && "grid-cols-4",
                                    viewMode === 'grid' && currentModalCols === 5 && "grid-cols-5",
                                    viewMode === 'grid' && currentModalCols === 6 && "grid-cols-6",
                                    viewMode === 'grid' && currentModalCols === 7 && "grid-cols-7",
                                    viewMode === 'grid' && currentModalCols === 8 && "grid-cols-8",
                                    viewMode === 'list' && currentModalCols === 1 && "grid-cols-1",
                                    viewMode === 'list' && currentModalCols === 2 && "grid-cols-2"
                                )}>
                                    {historyVideos.map((item, index) => (
                                        <div 
                                            key={`${item.generation.id}-${index}`}
                                            className="group relative aspect-video bg-background rounded-lg border border-border overflow-hidden hover:border-blue-500 transition-all cursor-pointer"
                                            onClick={() => onPreview({ url: item.url, type: 'video', generation: item.generation })}
                                        >
                                            <video src={item.url} className="w-full h-full object-cover opacity-60 group-hover:opacity-100 transition-opacity pointer-events-none" />
                                            <div className="absolute inset-0 flex items-center justify-center bg-black/20 group-hover:bg-black/40 transition-colors pointer-events-none">
                                                <div className="w-8 h-8 rounded-full bg-white/20 backdrop-blur-sm flex items-center justify-center group-hover:scale-110 transition-transform">
                                                    <Play size={16} className="fill-white text-foreground ml-1" />
                                                </div>
                                            </div>
                                            <div className="absolute top-2 left-2 bg-black/60 backdrop-blur-sm px-2 py-1 rounded text-[10px] text-white/60 font-mono">
                                                {new Date(item.generation.timestamp).toLocaleTimeString()}
                                            </div>
                                            <Button 
                                                variant="ghost"
                                                size="icon"
                                                onClick={(e) => {
                                                    e.stopPropagation();
                                                    onCollectVideo?.(containerId, item.url);
                                                }}
                                                className="absolute top-2 right-2 w-7 h-7 p-0 rounded bg-black/60 hover:bg-blue-500 text-white backdrop-blur-sm transition-colors opacity-0 group-hover:opacity-100 z-10 border-none"
                                                title="收藏 (移入可用)"
                                            >
                                                <Heart size={14} />
                                            </Button>
                                        </div>
                                    ))}
                                </div>
                            </div>
                        )}
                    </div>
                )}
            </ContentWrapper>
        </div>
        </>
    );
}
