import React, { useState, useCallback } from 'react';
import { BaseNode } from '../BaseNode';
import { NodePort } from '../../../types/canvas';
import { useCanvasStore } from '../../../store/canvasStore';
import { batchProcessor, BatchItem } from '../../../utils/batchProcessor';

interface FolderUploadNodeProps {
  id: string;
  data: {
    files?: File[];
    fileCount?: number;
    totalSize?: number;
    result?: File[];
  };
}

export const FolderUploadNode: React.FC<FolderUploadNodeProps> = ({ id, data }) => {
  const [files, setFiles] = useState<File[]>(data.files || []);
  const [isProcessing, setIsProcessing] = useState(false);
  const [batchResults, setBatchResults] = useState<BatchItem[]>([]);
  const { updateNode } = useCanvasStore();

  const outputs: NodePort[] = [
    { id: 'batch-output', type: 'batch', label: '批量输出', position: 'output' }
  ];

  const handleFolderChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    const selectedFiles = Array.from(e.target.files || []);
    const imageFiles = selectedFiles.filter(file => file.type.startsWith('image/'));

    setFiles(imageFiles);
    setBatchResults([]); // 清空之前的结果

    const totalSize = imageFiles.reduce((sum, file) => sum + file.size, 0);

    // 准备批量数据
    const batchData = imageFiles.map(file => ({
      filename: file.name,
      data: file,
      size: file.size,
      type: file.type
    }));

    // 更新节点数据
    updateNode(id, {
      data: {
        ...data,
        files: imageFiles,
        fileCount: imageFiles.length,
        totalSize,
        result: batchData
      }
    });
  }, [id, data, updateNode]);

  const formatFileSize = (bytes: number) => {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  return (
    <BaseNode
      id={id}
      title="文件夹上传"
      outputs={outputs}
    >
      <div className="space-y-2">
        <input
          type="file"
          multiple
          {...({ webkitdirectory: "" } as any)}
          onChange={handleFolderChange}
          className="w-full text-xs file:mr-2 file:py-1 file:px-2 file:rounded file:border-0 file:text-xs file:bg-orange-50 file:text-orange-700 hover:file:bg-orange-100"
        />
        
        {files.length > 0 ? (
          <div className="bg-orange-50 p-2 rounded text-xs">
            <div className="font-medium text-orange-800">
              📁 {files.length} 个图片文件
            </div>
            <div className="text-orange-600">
              总大小: {formatFileSize(data.totalSize || 0)}
            </div>

            {/* 文件列表预览 */}
            <div className="mt-2 max-h-20 overflow-y-auto">
              {files.slice(0, 5).map((file, index) => (
                <div key={index} className="text-orange-600 truncate text-xs">
                  • {file.name} ({formatFileSize(file.size)})
                </div>
              ))}
              {files.length > 5 && (
                <div className="text-orange-500 text-xs">
                  ... 还有 {files.length - 5} 个文件
                </div>
              )}
            </div>

            {/* 批量处理状态 */}
            {isProcessing && (
              <div className="mt-2 text-blue-600">
                <div className="flex items-center space-x-1">
                  <div className="w-2 h-2 bg-blue-500 rounded-full animate-pulse"></div>
                  <span>批量处理中...</span>
                </div>
              </div>
            )}

            {/* 批量结果预览 */}
            {batchResults.length > 0 && (
              <div className="mt-2">
                <div className="text-green-600 font-medium">
                  处理完成: {batchResults.filter(r => r.status === 'success').length}/{batchResults.length}
                </div>
                <div className="grid grid-cols-3 gap-1 mt-1 max-h-16 overflow-y-auto">
                  {batchResults.slice(0, 6).map((result, index) => (
                    <div
                      key={result.id}
                      className={`w-full h-8 rounded border text-xs flex items-center justify-center ${
                        result.status === 'success' ? 'bg-green-100 text-green-700' :
                        result.status === 'error' ? 'bg-red-100 text-red-700' :
                        'bg-blue-100 text-blue-700'
                      }`}
                    >
                      {result.status === 'success' ? '✓' :
                       result.status === 'error' ? '✗' : '⏳'}
                    </div>
                  ))}
                </div>
              </div>
            )}
          </div>
        ) : (
          <div className="w-full h-20 border-2 border-dashed border-orange-300 rounded flex items-center justify-center text-xs text-orange-400">
            选择包含图片的文件夹
          </div>
        )}
      </div>
    </BaseNode>
  );
};
