'use client';

import { useEffect, useState } from 'react';
import { Loader2, CheckCircle2, XCircle, Clock } from 'lucide-react';
import { DefaultService } from '@/lib/api';
import { ProjectData, InitializationProgress as IProgress } from '@/types';
import { Button } from '@/components/ui/button';

interface InitializationProgressProps {
  projectId: string;
  onComplete: (project: ProjectData) => void;
  onError: (error: any) => void;
}

export function InitializationProgress({
  projectId,
  onComplete,
  onError
}: InitializationProgressProps) {
  const [project, setProject] = useState<ProjectData | null>(null);
  const [progress, setProgress] = useState<IProgress | null>(null);
  const [elapsedTime, setElapsedTime] = useState(0);

  // Poll for progress
  useEffect(() => {
    let pollInterval: NodeJS.Timeout;
    let timeInterval: NodeJS.Timeout;

    const poll = async () => {
      try {
        const response = await DefaultService.getProject(projectId);
        const data = (response as any).data as ProjectData;
        setProject(data);
        setProgress(data.progress || null);

        if (data.status === 'active') {
          clearInterval(pollInterval);
          clearInterval(timeInterval);
          onComplete(data);
        } else if (data.status === 'failed') {
          clearInterval(pollInterval);
          clearInterval(timeInterval);
          onError(data.error || { message: '初始化失败' });
        }
      } catch (error) {
        console.error('Failed to poll progress:', error);
      }
    };

    // Start polling every 2 seconds
    poll(); // Initial poll
    pollInterval = setInterval(poll, 2000);

    // Track elapsed time
    timeInterval = setInterval(() => {
      setElapsedTime(prev => prev + 1);
    }, 1000);

    return () => {
      clearInterval(pollInterval);
      clearInterval(timeInterval);
    };
  }, [projectId, onComplete, onError]);

  const formatTime = (seconds: number) => {
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${mins}:${secs.toString().padStart(2, '0')}`;
  };

  const getStepIcon = (step: string) => {
    const completed = progress && progress.percentage > 0;
    if (completed) {
      return <CheckCircle2 className="w-5 h-5 text-green-500" />;
    }
    return <Loader2 className="w-5 h-5 animate-spin text-blue-500" />;
  };

  const steps = [
    { key: 'starting', label: '启动初始化', percentage: 5 },
    { key: 'analyzing', label: 'AI 分析文本', percentage: 10 },
    { key: 'splitting_chapters', label: '拆分章节', percentage: 20 },
    { key: 'summarizing', label: '生成摘要', percentage: 30 },
    { key: 'extracting_assets', label: '提取资产', percentage: 55 },
    { key: 'generating_storyboards', label: '生成分镜', percentage: 65 },
    { key: 'processing_assets', label: '处理数据', percentage: 70 },
    { key: 'finalizing', label: '保存项目', percentage: 95 }
  ];

  const currentStepIndex = steps.findIndex(s => s.key === progress?.current_step);

  return (
    <div className="flex flex-col items-center justify-center min-h-[500px] p-8">
      {/* Main Progress Circle */}
      <div className="relative w-32 h-32 mb-8">
        <svg className="w-full h-full transform -rotate-90">
          <circle
            cx="64"
            cy="64"
            r="56"
            stroke="currentColor"
            strokeWidth="8"
            fill="none"
            className="text-gray-200"
          />
          <circle
            cx="64"
            cy="64"
            r="56"
            stroke="currentColor"
            strokeWidth="8"
            fill="none"
            strokeDasharray={`${2 * Math.PI * 56}`}
            strokeDashoffset={`${2 * Math.PI * 56 * (1 - (progress?.percentage || 0) / 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-2xl font-bold text-foreground">
            {progress?.percentage || 0}%
          </span>
        </div>
      </div>

      {/* Current Step Message */}
      <div className="text-center mb-8">
        <h3 className="text-lg font-semibold text-foreground mb-2">
          {progress?.message || '正在初始化...'}
        </h3>
        {progress?.details && Object.keys(progress.details).length > 0 && (
          <div className="flex items-center justify-center gap-4 text-sm text-muted-foreground">
            {progress.details.characters_count !== undefined && (
              <span>角色: {progress.details.characters_count}</span>
            )}
            {progress.details.scenes_count !== undefined && (
              <span>场景: {progress.details.scenes_count}</span>
            )}
            {progress.details.props_count !== undefined && (
              <span>道具: {progress.details.props_count}</span>
            )}
            {progress.details.chapters_count !== undefined && (
              <span>章节: {progress.details.chapters_count}</span>
            )}
          </div>
        )}
      </div>

      {/* Step List */}
      <div className="w-full max-w-md space-y-2 mb-6">
        {steps.map((step, index) => {
          const isCompleted = (progress?.percentage || 0) >= step.percentage;
          const isCurrent = step.key === progress?.current_step;
          
          return (
            <div
              key={step.key}
              className={`flex items-center gap-3 p-3 rounded-lg transition-all ${
                isCurrent
                  ? 'bg-blue-500/10 border border-blue-500/20'
                  : isCompleted
                  ? 'bg-green-500/5'
                  : 'bg-muted/30'
              }`}
            >
              {isCompleted ? (
                <CheckCircle2 className="w-5 h-5 text-green-500 shrink-0" />
              ) : isCurrent ? (
                <Loader2 className="w-5 h-5 animate-spin text-blue-500 shrink-0" />
              ) : (
                <div className="w-5 h-5 rounded-full border-2 border-gray-300 shrink-0" />
              )}
              <span
                className={`text-sm ${
                  isCurrent
                    ? 'text-foreground font-medium'
                    : isCompleted
                    ? 'text-muted-foreground'
                    : 'text-muted-foreground/50'
                }`}
              >
                {step.label}
              </span>
            </div>
          );
        })}
      </div>

      {/* Elapsed Time */}
      <div className="flex items-center gap-2 text-sm text-muted-foreground">
        <Clock className="w-4 h-4" />
        <span>已用时: {formatTime(elapsedTime)}</span>
      </div>

      {/* Tips */}
      <div className="mt-8 p-4 bg-blue-500/5 border border-blue-500/20 rounded-lg max-w-md">
        <p className="text-xs text-muted-foreground text-center">
          💡 初始化过程可能需要 2-5 分钟，具体时间取决于文本长度。您可以离开此页面，我们会在完成后通知您。
        </p>
      </div>
    </div>
  );
}
