import React, { useEffect, useState } from 'react';
import { Film, Trash2, Clock, Loader2 } from 'lucide-react';
import { Card, CardContent, CardFooter } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { cn } from '@/utils';
import { ProjectData } from '@/types';
import { DefaultService } from '@/lib/api';
import Link from 'next/link';

interface ProjectCardProps {
    project: ProjectData;
    viewMode: 'grid' | 'list';
    onDelete: (e: React.MouseEvent, id: string) => void;
    onUpdate?: (project: ProjectData) => void;
}

export function ProjectCard({ project: initialProject, viewMode, onDelete, onUpdate }: ProjectCardProps) {
    const [project, setProject] = useState(initialProject);
    const isInitializing = project.status === 'initializing';
    
    // Poll for progress if initializing
    useEffect(() => {
        if (!isInitializing) return;
        
        const pollInterval = setInterval(async () => {
            try {
                const response = await DefaultService.getProject(project.id);
                const updated = (response as any).data as ProjectData;
                setProject(updated);
                
                // Notify parent of update
                if (onUpdate) {
                    onUpdate(updated);
                }
                
                // Stop polling if no longer initializing
                if (updated.status !== 'initializing') {
                    clearInterval(pollInterval);
                }
            } catch (error) {
                console.error('Failed to poll project progress:', error);
            }
        }, 2000);
        
        return () => clearInterval(pollInterval);
    }, [isInitializing, project.id, onUpdate]);
    
    // Update when prop changes
    useEffect(() => {
        setProject(initialProject);
    }, [initialProject]);
    
    const CardWrapper = ({ children, className }: { children: React.ReactNode, className?: string }) => {
        if (isInitializing) {
             return <div className={cn("block opacity-80 cursor-not-allowed relative", className)}>{children}</div>;
        }
        return <Link href={`/project/${project.id}`} className={cn("block group", className)}>{children}</Link>;
    };

    const StatusBadge = () => {
        if (isInitializing && project.progress) {
            return (
                <div className="flex items-center gap-2">
                    {/* Circular Progress */}
                    <div className="relative w-8 h-8">
                        <svg className="w-full h-full transform -rotate-90">
                            <circle
                                cx="16"
                                cy="16"
                                r="14"
                                stroke="currentColor"
                                strokeWidth="2"
                                fill="none"
                                className="text-gray-200"
                            />
                            <circle
                                cx="16"
                                cy="16"
                                r="14"
                                stroke="currentColor"
                                strokeWidth="2"
                                fill="none"
                                strokeDasharray={`${2 * Math.PI * 14}`}
                                strokeDashoffset={`${2 * Math.PI * 14 * (1 - project.progress.percentage / 100)}`}
                                className="text-blue-500 transition-all duration-500"
                                strokeLinecap="round"
                            />
                        </svg>
                        <div className="absolute inset-0 flex items-center justify-center">
                            <span className="text-[10px] font-bold text-foreground">
                                {project.progress.percentage}%
                            </span>
                        </div>
                    </div>
                    <div className="flex flex-col">
                        <span className="text-xs text-blue-500 font-medium">初始化中</span>
                        <span className="text-[10px] text-muted-foreground">{project.progress.message}</span>
                    </div>
                </div>
            );
        }
        
        if (isInitializing) {
            return (
                <div className="flex items-center gap-1.5 text-blue-500">
                    <Loader2 className="h-3 w-3 animate-spin" />
                    <span className="text-xs">初始化中...</span>
                </div>
            );
        }
        
        return (
            <div className={`w-2 h-2 rounded-full ${project.status === 'active' ? 'bg-green-500' : 'bg-gray-500'}`} />
        );
    };
    
    // 步骤名称中文映射
    const getStepLabel = (step: string): string => {
        const stepLabels: Record<string, string> = {
            'starting': '启动中',
            'analyzing': '分析文本',
            'summarizing_chapters': '总结章节',
            'extracting_characters': '提取角色',
            'extracting_scenes': '提取场景',
            'extracting_props': '提取道具',
            'generating_storyboards': '生成分镜',
            'processing_assets': '处理资产',
            'finalizing': '完成初始化',
        };
        return stepLabels[step] || step;
    };
    
    const ProgressDetails = () => {
        if (!isInitializing || !project.progress) return null;
        
        return (
            <div className="mt-2 pt-2 border-t border-border/50">
                <div className="flex items-center justify-between text-xs">
                    <span className="text-muted-foreground">{getStepLabel(project.progress.current_step)}</span>
                    {project.progress.details && (
                        <span className="text-muted-foreground">
                            {project.progress.details.characters && `角色: ${project.progress.details.characters} `}
                            {project.progress.details.scenes && `场景: ${project.progress.details.scenes} `}
                            {project.progress.details.props && `道具: ${project.progress.details.props}`}
                        </span>
                    )}
                </div>
            </div>
        );
    };

    if (viewMode === 'list') {
        return (
            <CardWrapper>
                <Card className="flex flex-row h-32 overflow-hidden hover:shadow-lg transition-all border-border/40 hover:border-border bg-card">
                    {/* Thumbnail */}
                    <div className="w-48 bg-muted relative shrink-0 group-hover:bg-muted/80 transition-colors flex items-center justify-center">
                        <Film className="opacity-20 w-8 h-8" />
                        {!isInitializing && (
                            <div className="absolute top-2 left-2 z-20">
                                <Button
                                    variant="destructive"
                                    size="icon"
                                    className="h-6 w-6 opacity-0 group-hover:opacity-100 transition-opacity"
                                    onClick={(e) => {
                                        e.preventDefault();
                                        onDelete(e, project.id);
                                    }}
                                >
                                    <Trash2 className="h-3 w-3" />
                                </Button>
                            </div>
                        )}
                        {/* 初始化状态显示在缩略图中心 */}
                        {isInitializing && (
                            <div className="absolute inset-0 bg-black/10 flex items-center justify-center">
                                {project.progress ? (
                                    <StatusBadge />
                                ) : (
                                    <Loader2 className="h-6 w-6 animate-spin text-primary" />
                                )}
                            </div>
                        )}
                    </div>
                    
                    {/* Content */}
                    <div className="flex-1 p-4 flex flex-col justify-between">
                        <div className="flex justify-between items-start">
                            <div className="flex-1">
                                <h3 className="font-medium text-foreground group-hover:text-primary transition-colors truncate">
                                    {project.name}
                                </h3>
                                <p className="text-sm text-muted-foreground mt-1 line-clamp-1">
                                    {project.description || '暂无描述'}
                                </p>
                            </div>
                            <Badge variant="outline" className="uppercase text-[10px] ml-2">
                                {project.type}
                            </Badge>
                        </div>
                        
                        <div className="space-y-2">
                            <div className="flex items-center text-xs text-muted-foreground gap-4">
                                <span className="flex items-center gap-1">
                                    <Clock className="h-3 w-3" />
                                    {new Date(project.updated_at).toLocaleDateString()}
                                </span>
                                {/* 非初始化状态显示状态点 */}
                                {!isInitializing && <StatusBadge />}
                            </div>
                            {/* 初始化时不显示进度详情 */}
                            {!isInitializing && <ProgressDetails />}
                        </div>
                    </div>
                </Card>
            </CardWrapper>
        );
    }

    return (
        <CardWrapper>
            <Card className="overflow-hidden hover:shadow-xl transition-all border-border/40 hover:border-border bg-card h-full flex flex-col">
                {/* Thumbnail */}
                <div className="h-40 bg-muted relative group-hover:bg-muted/80 transition-colors flex items-center justify-center">
                    <Film className="opacity-20 w-10 h-10" />
                    
                    <div className="absolute top-2 right-2">
                         <Badge variant="secondary" className="uppercase text-[10px] bg-black/50 backdrop-blur-sm text-white/70 border-white/10">
                            {project.type}
                        </Badge>
                    </div>

                    {!isInitializing && (
                        <div className="absolute top-2 left-2 z-20">
                            <Button
                                variant="destructive"
                                size="icon"
                                className="h-7 w-7 opacity-0 group-hover:opacity-100 transition-opacity"
                                onClick={(e) => {
                                    e.preventDefault();
                                    onDelete(e, project.id);
                                }}
                            >
                                <Trash2 className="h-3.5 w-3.5" />
                            </Button>
                        </div>
                    )}
                    
                    {/* 初始化状态显示在缩略图中心 */}
                    {isInitializing && (
                        <div className="absolute inset-0 bg-black/10 flex items-center justify-center">
                            {project.progress ? (
                                <StatusBadge />
                            ) : (
                                <Loader2 className="h-8 w-8 animate-spin text-primary" />
                            )}
                        </div>
                    )}
                </div>

                {/* Content */}
                <CardContent className="p-4 flex-1">
                    <h3 className="font-medium text-foreground group-hover:text-primary transition-colors truncate">
                        {project.name}
                    </h3>
                    <p className="text-sm text-muted-foreground mt-1 line-clamp-2">
                        {project.description || '暂无描述'}
                    </p>
                </CardContent>

                <CardFooter className="p-4 pt-0 flex flex-col gap-2">
                    <div className="w-full flex justify-between items-center text-xs text-muted-foreground">
                        <span className="flex items-center gap-1">
                            <Clock className="h-3 w-3" />
                            {new Date(project.updated_at).toLocaleDateString()}
                        </span>
                        {/* 非初始化状态显示状态点 */}
                        {!isInitializing && <StatusBadge />}
                    </div>
                    {/* 初始化时不显示进度详情 */}
                    {!isInitializing && <ProgressDetails />}
                </CardFooter>
            </Card>
        </CardWrapper>
    );
}
