'use client';

import React, { useMemo } from 'react';
import { useReactFlow, useNodes } from '@xyflow/react';
import { Film, Loader2, CheckCircle2, XCircle, Image as ImageIcon } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { ScrollArea } from '@/components/ui/scroll-area';
import { SecureImage } from '@/components/common/SecureImage';
import { AppNodeType, AppNodeData, NodeStatus, NodeType } from '@/components/canvas/types/node';
import { cn } from '@/utils';

interface StoryboardShot {
  id: string;
  title: string;
  status: NodeStatus;
  image?: string;
  prompt?: string;
  position: { x: number; y: number };
  isCharacterRef?: boolean;
}

interface StoryboardPreviewProps {
  className?: string;
}

/**
 * Storyboard Preview Panel
 * 
 * Displays all storyboard shots in a grid with thumbnails, titles, and status.
 * Allows clicking on shots to navigate to the corresponding node on the canvas.
 * 
 * Features:
 * - Real-time status updates
 * - Thumbnail previews
 * - Click to navigate to node
 * - Character reference identification
 * - Progress tracking
 */
export const StoryboardPreview: React.FC<StoryboardPreviewProps> = ({ className }) => {
  // Use React Flow's useNodes hook instead of Canvas Store
  const nodes = useNodes<AppNodeType>();
  const { setCenter, getNode } = useReactFlow();

  /**
   * Extract storyboard shots from nodes
   * Identifies nodes that are part of a storyboard workflow
   */
  const storyboardShots = useMemo(() => {
    const shots: StoryboardShot[] = [];
    
    // Filter nodes that are IMAGE_GENERATOR or VIDEO_GENERATOR type
    const mediaNodes = nodes.filter(node => {
      if (node.type !== 'appNode') return false;
      const data = node.data as AppNodeData;
      return data.type === NodeType.IMAGE_GENERATOR || data.type === NodeType.VIDEO_GENERATOR;
    });

    mediaNodes.forEach(node => {
      const data = node.data as AppNodeData;
      const title = data.title || '';
      
      // Check if this is a storyboard-related node
      // Auto-generated nodes have specific title patterns:
      // - Asset: "角色 图片: XXX", "场景 图片: XXX", "道具 图片: XXX"
      // - Storyboard: "分镜N 图片", "分镜N 视频"
      const isAssetNode = title.includes('角色') || title.includes('场景') || title.includes('道具');
      const isStoryboardNode = title.includes('分镜');
      
      // Only include storyboard nodes and asset nodes (as character references)
      if (isAssetNode || isStoryboardNode) {
        shots.push({
          id: node.id,
          title,
          status: data.status as NodeStatus,
          image: data.type === NodeType.IMAGE_GENERATOR ? data.image : undefined,
          prompt: data.prompt,
          position: node.position,
          isCharacterRef: isAssetNode, // Assets are character/scene/prop references
        });
      }
    });

    // Sort: character reference first, then shots by title
    shots.sort((a, b) => {
      if (a.isCharacterRef && !b.isCharacterRef) return -1;
      if (!a.isCharacterRef && b.isCharacterRef) return 1;
      return a.title.localeCompare(b.title);
    });

    return shots;
  }, [nodes]);

  /**
   * Calculate progress statistics
   */
  const stats = useMemo(() => {
    const total = storyboardShots.length;
    const completed = storyboardShots.filter(s => s.status === NodeStatus.SUCCESS).length;
    const working = storyboardShots.filter(s => s.status === NodeStatus.WORKING).length;
    const failed = storyboardShots.filter(s => s.status === NodeStatus.ERROR).length;
    const idle = storyboardShots.filter(s => s.status === NodeStatus.IDLE).length;
    
    return { total, completed, working, failed, idle };
  }, [storyboardShots]);

  /**
   * Navigate to node on canvas
   */
  const handleShotClick = (shot: StoryboardShot) => {
    const node = getNode(shot.id);
    if (node) {
      // Center the view on the node with zoom
      setCenter(
        node.position.x + (node.width || 300) / 2,
        node.position.y + (node.height || 200) / 2,
        { zoom: 1, duration: 500 }
      );
    }
  };

  /**
   * Get status icon and color
   */
  const getStatusDisplay = (status: NodeStatus) => {
    switch (status) {
      case NodeStatus.SUCCESS:
        return { icon: CheckCircle2, color: 'text-green-500', label: '完成' };
      case NodeStatus.WORKING:
        return { icon: Loader2, color: 'text-blue-500 animate-spin', label: '生成中' };
      case NodeStatus.ERROR:
        return { icon: XCircle, color: 'text-red-500', label: '失败' };
      case NodeStatus.IDLE:
      default:
        return { icon: ImageIcon, color: 'text-gray-400', label: '待生成' };
    }
  };

  // Show panel only if there are storyboard shots
  const shouldShow = storyboardShots.length > 0;
  
  // Show empty state if no storyboard shots
  if (!shouldShow) {
    return (
      <Card className={cn('w-64 h-auto flex flex-col shadow-lg', className)}>
        <CardHeader className="pb-2 px-4 pt-4">
          <CardTitle className="text-sm flex items-center gap-2">
            <Film className="w-4 h-4" />
            分镜预览
          </CardTitle>
        </CardHeader>
        <CardContent className="px-4 pb-4">
          <p className="text-xs text-muted-foreground">
            当前画布暂无分镜节点
          </p>
          <p className="text-[10px] text-muted-foreground mt-1.5 leading-relaxed">
            切换到分镜画布后，会自动生成分镜工作流
          </p>
        </CardContent>
      </Card>
    );
  }

  return (
    <Card className={cn('w-64 max-h-[80vh] flex flex-col shadow-lg', className)}>
      <CardHeader className="pb-2 px-4 pt-4">
        <div className="flex items-center justify-between">
          <CardTitle className="text-sm flex items-center gap-2">
            <Film className="w-4 h-4" />
            分镜预览
          </CardTitle>
          <Badge variant="secondary" className="text-xs px-1.5 py-0.5">
            {stats.completed}/{stats.total}
          </Badge>
        </div>
        
        {/* Progress bar */}
        {stats.total > 0 && (
          <div className="mt-2 space-y-1">
            <div className="h-1.5 bg-secondary rounded-full overflow-hidden">
              <div
                className="h-full bg-primary transition-all duration-500"
                style={{ width: `${(stats.completed / stats.total) * 100}%` }}
              />
            </div>
            <div className="flex items-center justify-between text-[10px] text-muted-foreground">
              <span>{Math.round((stats.completed / stats.total) * 100)}%</span>
              {stats.working > 0 && (
                <span className="text-blue-500 flex items-center gap-0.5">
                  <Loader2 className="w-2.5 h-2.5 animate-spin" />
                  {stats.working}
                </span>
              )}
            </div>
          </div>
        )}
      </CardHeader>

      <CardContent className="flex-1 overflow-hidden p-0">
        <ScrollArea className="h-full px-4 pb-4">
          <div className="space-y-2">
            {storyboardShots.map((shot) => {
              const statusDisplay = getStatusDisplay(shot.status);
              const StatusIcon = statusDisplay.icon;

              return (
                <div
                  key={shot.id}
                  onClick={() => handleShotClick(shot)}
                  className={cn(
                    'group relative rounded-lg border bg-card overflow-hidden cursor-pointer',
                    'transition-all duration-200 hover:shadow-md hover:border-primary/50 hover:scale-[1.02]',
                    shot.status === NodeStatus.WORKING && 'border-blue-500/50 shadow-sm',
                    shot.status === NodeStatus.SUCCESS && 'border-green-500/30',
                    shot.status === NodeStatus.ERROR && 'border-red-500/50'
                  )}
                >
                  {/* Thumbnail */}
                  <div className="relative aspect-video bg-secondary/50 overflow-hidden">
                    {shot.image ? (
                      <SecureImage
                        src={shot.image}
                        alt={shot.title}
                        className="w-full h-full object-cover"
                      />
                    ) : (
                      <div className="w-full h-full flex items-center justify-center">
                        <StatusIcon className={cn('w-6 h-6', statusDisplay.color)} />
                      </div>
                    )}
                    
                    {/* Status badge - smaller */}
                    <div className="absolute top-1 right-1">
                      <div className={cn(
                        'flex items-center gap-0.5 px-1.5 py-0.5 rounded text-[10px] font-medium',
                        'bg-background/90 backdrop-blur-sm border',
                        shot.status === NodeStatus.SUCCESS && 'border-green-500/50 text-green-600',
                        shot.status === NodeStatus.WORKING && 'border-blue-500/50 text-blue-600',
                        shot.status === NodeStatus.ERROR && 'border-red-500/50 text-red-600',
                        shot.status === NodeStatus.IDLE && 'border-gray-300 text-gray-600'
                      )}>
                        <StatusIcon className={cn('w-2.5 h-2.5', statusDisplay.color)} />
                        <span className="hidden group-hover:inline">{statusDisplay.label}</span>
                      </div>
                    </div>

                    {/* Character reference badge */}
                    {shot.isCharacterRef && (
                      <div className="absolute top-1 left-1">
                        <Badge variant="default" className="text-[10px] px-1.5 py-0 h-5">
                          角色
                        </Badge>
                      </div>
                    )}

                    {/* Hover overlay */}
                    <div className="absolute inset-0 bg-black/0 group-hover:bg-black/10 transition-colors" />
                  </div>

                  {/* Info - more compact */}
                  <div className="p-2 space-y-0.5">
                    <h4 className="font-medium text-xs line-clamp-1">
                      {shot.title}
                    </h4>
                    {shot.prompt && (
                      <p className="text-[10px] text-muted-foreground line-clamp-1">
                        {shot.prompt}
                      </p>
                    )}
                  </div>
                </div>
              );
            })}
          </div>
        </ScrollArea>
      </CardContent>
    </Card>
  );
};

export default StoryboardPreview;
