import React, { useEffect, useState } from 'react';
import { X, CheckCircle, XCircle, Clock, Upload, AlertCircle } from 'lucide-react';
import { ImportProgress, ImportStatus } from '../../types/template';
import { useTemplateStore } from '../../stores/templateStore';

interface ImportProgressModalProps {
  templateId: string;
  onClose: () => void;
  onComplete?: () => void;
}

export const ImportProgressModal: React.FC<ImportProgressModalProps> = ({
  templateId,
  onClose,
  onComplete,
}) => {
  const [progress, setProgress] = useState<ImportProgress | null>(null);
  const [lastValidProgress, setLastValidProgress] = useState<ImportProgress | null>(null);
  const [hasCompleted, setHasCompleted] = useState(false);
  const { getImportProgress } = useTemplateStore();

  useEffect(() => {
    let interval: NodeJS.Timeout | null = null;
    let isMounted = true;

    const fetchProgress = async () => {
      if (!isMounted) return;

      try {
        const progressData = await getImportProgress(templateId);
        if (!isMounted) return;

        // 如果有有效的进度数据，保存它并更新显示
        if (progressData) {
          setProgress(progressData);
          setLastValidProgress(progressData);
        }

        // 检查是否导入完成
        const isCompleted = !progressData ||
                           progressData.status === ImportStatus.Completed ||
                           progressData.status === ImportStatus.Failed;

        if (isCompleted && !hasCompleted) {
          // 标记为已完成，避免重复处理
          setHasCompleted(true);

          // 如果进度数据为空但有最后有效进度，使用它
          if (!progressData && lastValidProgress) {
            const completedProgress: ImportProgress = {
              ...lastValidProgress,
              status: ImportStatus.Completed,
              current_operation: "导入完成",
              progress_percentage: 100
            };
            setProgress(completedProgress);
          }

          // 清除轮询
          if (interval) {
            clearInterval(interval);
            interval = null;
          }

          // 立即触发完成回调，然后延迟关闭弹窗
          if (onComplete && (progressData?.status === ImportStatus.Completed || !progressData)) {
            // 立即刷新列表
            onComplete();

            // 延迟关闭弹窗，让用户看到完成状态
            setTimeout(() => {
              if (isMounted) {
                onClose();
              }
            }, 2000);
          }
          return;
        }
      } catch (error) {
        console.error('获取导入进度失败:', error);
        // 如果出错，也停止轮询
        if (interval) {
          clearInterval(interval);
          interval = null;
        }
      }
    };

    // 立即获取一次进度
    fetchProgress();

    // 开始轮询
    interval = setInterval(fetchProgress, 1000);

    return () => {
      isMounted = false;
      if (interval) {
        clearInterval(interval);
      }
    };
  }, [templateId, getImportProgress, onComplete]);

  const getStatusIcon = (status: ImportStatus) => {
    switch (status) {
      case ImportStatus.Completed:
        return <CheckCircle className="w-6 h-6 text-green-500" />;
      case ImportStatus.Failed:
        return <XCircle className="w-6 h-6 text-red-500" />;
      case ImportStatus.Uploading:
        return <Upload className="w-6 h-6 text-blue-500 animate-pulse" />;
      case ImportStatus.Processing:
      case ImportStatus.Parsing:
        return <Clock className="w-6 h-6 text-blue-500 animate-spin" />;
      default:
        return <AlertCircle className="w-6 h-6 text-yellow-500" />;
    }
  };

  const getStatusText = (status: ImportStatus) => {
    switch (status) {
      case ImportStatus.Pending:
        return '等待开始';
      case ImportStatus.Parsing:
        return '解析模板文件';
      case ImportStatus.Uploading:
        return '上传素材文件';
      case ImportStatus.Processing:
        return '处理模板数据';
      case ImportStatus.Completed:
        return '导入完成';
      case ImportStatus.Failed:
        return '导入失败';
      default:
        return '未知状态';
    }
  };

  const getStatusColor = (status: ImportStatus) => {
    switch (status) {
      case ImportStatus.Completed:
        return 'text-green-600';
      case ImportStatus.Failed:
        return 'text-red-600';
      case ImportStatus.Uploading:
      case ImportStatus.Processing:
      case ImportStatus.Parsing:
        return 'text-blue-600';
      default:
        return 'text-yellow-600';
    }
  };

  if (!progress) {
    return (
      <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
        <div className="bg-white rounded-lg shadow-xl w-full max-w-md mx-4 p-6">
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-xl font-semibold text-gray-900">模板导入</h2>
            <button
              onClick={onClose}
              className="text-gray-400 hover:text-gray-600 transition-colors"
            >
              <X className="w-6 h-6" />
            </button>
          </div>

          <div className="flex items-center justify-center py-8">
            <CheckCircle className="w-12 h-12 text-green-500 mr-4" />
            <div>
              <div className="text-lg font-medium text-green-600">导入完成！</div>
              <div className="text-sm text-gray-600">模板已成功导入到系统中</div>
            </div>
          </div>

          <div className="flex justify-end">
            <button
              onClick={onClose}
              className="px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700 transition-colors"
            >
              完成
            </button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div className="bg-white rounded-lg shadow-xl w-full max-w-md mx-4">
        {/* 模态框头部 */}
        <div className="flex items-center justify-between p-6 border-b border-gray-200">
          <h2 className="text-xl font-semibold text-gray-900">导入进度</h2>
          <button
            onClick={onClose}
            className="p-1 rounded-full hover:bg-gray-100 transition-colors"
          >
            <X className="w-5 h-5 text-gray-500" />
          </button>
        </div>

        {/* 模态框内容 */}
        <div className="p-6">
          {/* 模板信息 */}
          <div className="mb-6">
            <h3 className="text-lg font-medium text-gray-900 mb-2">
              {progress.template_name}
            </h3>
            <div className="text-sm text-gray-600">
              模板ID: {progress.template_id}
            </div>
          </div>

          {/* 状态指示器 */}
          <div className="flex items-center mb-6">
            {getStatusIcon(progress.status)}
            <div className="ml-3">
              <div className={`text-lg font-medium ${getStatusColor(progress.status)}`}>
                {getStatusText(progress.status)}
              </div>
              <div className="text-sm text-gray-600">
                {progress.current_operation}
              </div>
            </div>
          </div>

          {/* 进度条 */}
          <div className="mb-6">
            <div className="flex items-center justify-between mb-2">
              <span className="text-sm font-medium text-gray-700">总体进度</span>
              <span className="text-sm text-gray-600">
                {Math.round(progress.progress_percentage)}%
              </span>
            </div>
            <div className="w-full bg-gray-200 rounded-full h-2">
              <div
                className={`h-2 rounded-full transition-all duration-300 ${
                  progress.status === ImportStatus.Failed
                    ? 'bg-red-500'
                    : progress.status === ImportStatus.Completed
                    ? 'bg-green-500'
                    : 'bg-blue-500'
                }`}
                style={{ width: `${Math.min(100, Math.max(0, progress.progress_percentage))}%` }}
              />
            </div>
          </div>

          {/* 素材统计 */}
          <div className="grid grid-cols-3 gap-4 mb-6">
            <div className="text-center">
              <div className="text-lg font-semibold text-gray-900">
                {progress.total_materials}
              </div>
              <div className="text-xs text-gray-500">总素材</div>
            </div>
            <div className="text-center">
              <div className="text-lg font-semibold text-green-600">
                {progress.uploaded_materials}
              </div>
              <div className="text-xs text-gray-500">已完成</div>
            </div>
            <div className="text-center">
              <div className="text-lg font-semibold text-red-600">
                {progress.failed_materials}
              </div>
              <div className="text-xs text-gray-500">失败</div>
            </div>
          </div>

          {/* 错误信息 */}
          {progress.error_message && (
            <div className="mb-6 p-4 bg-red-50 border border-red-200 rounded-lg">
              <div className="flex items-start">
                <XCircle className="w-5 h-5 text-red-500 mr-2 mt-0.5 flex-shrink-0" />
                <div className="text-sm text-red-800">
                  <div className="font-medium mb-1">导入失败</div>
                  <div>{progress.error_message}</div>
                </div>
              </div>
            </div>
          )}

          {/* 成功信息 */}
          {progress.status === ImportStatus.Completed && (
            <div className="mb-6 p-4 bg-green-50 border border-green-200 rounded-lg">
              <div className="flex items-center">
                <CheckCircle className="w-5 h-5 text-green-500 mr-2" />
                <div className="text-sm text-green-800">
                  <div className="font-medium">导入成功！</div>
                  <div>模板已成功导入到系统中</div>
                </div>
              </div>
            </div>
          )}
        </div>

        {/* 模态框底部 */}
        <div className="flex items-center justify-end p-6 border-t border-gray-200">
          {progress.status === ImportStatus.Completed || progress.status === ImportStatus.Failed ? (
            <button
              onClick={onClose}
              className="px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700 transition-colors"
            >
              完成
            </button>
          ) : (
            <button
              onClick={onClose}
              className="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
            >
              后台运行
            </button>
          )}
        </div>
      </div>
    </div>
  );
};
