
import React, { useState, useRef, useCallback } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { Material } from '@/api/entities';
import { UploadFile } from '@/api/integrations';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Upload, Image, Check, Loader2, X, HelpCircle } from 'lucide-react';
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip";

export default function BatchUploader({ title, description, materialType, onUploadComplete }) {
  const [dragActive, setDragActive] = useState(false);
  const [uploadQueue, setUploadQueue] = useState([]);
  const fileInputRef = useRef(null);

  const handleDrag = useCallback((e) => {
    e.preventDefault();
    e.stopPropagation();
    if (e.type === 'dragenter' || e.type === 'dragover') {
      setDragActive(true);
    } else if (e.type === 'dragleave') {
      setDragActive(false);
    }
  }, []);

  const handleDrop = useCallback((e) => {
    e.preventDefault();
    e.stopPropagation();
    setDragActive(false);
    handleFiles(Array.from(e.dataTransfer.files));
  }, [materialType, onUploadComplete]); // Added onUploadComplete to dependencies

  const handleFileInput = (e) => {
    handleFiles(Array.from(e.target.files));
    e.target.value = ''; // Reset file input
  };

  const handleFiles = (files) => {
    const newQueueItems = files.map(file => ({
      file,
      id: `${file.name}-${file.lastModified}-${Math.random()}`,
      status: 'pending',
      progress: 0,
      error: null,
    }));
    setUploadQueue(prev => [...newQueueItems, ...prev]);
    processQueue(newQueueItems);
  };
  
  const processQueue = async (itemsToProcess) => {
    for (const item of itemsToProcess) {
      await processFile(item);
    }
    // Call onUploadComplete after all files are processed
    if (onUploadComplete) {
      onUploadComplete();
    }
  };

  const processFile = async (queueItem) => {
     setUploadQueue(prev => prev.map(item =>
        item.id === queueItem.id ? { ...item, status: 'uploading' } : item
      ));

    try {
      const { file_url } = await UploadFile({ file: queueItem.file });
      
       setUploadQueue(prev => prev.map(item =>
        item.id === queueItem.id ? { ...item, progress: 50 } : item
      ));

      await Material.create({
        name: queueItem.file.name.split('.').slice(0, -1).join('.'), // Use filename as name
        type: materialType,
        file_url,
      });

      setUploadQueue(prev => prev.map(item =>
        item.id === queueItem.id ? { ...item, status: 'completed', progress: 100 } : item
      ));
    } catch (error) {
      console.error("Upload error:", error);
      setUploadQueue(prev => prev.map(item =>
        item.id === queueItem.id ? { ...item, status: 'error', error: '上传失败' } : item
      ));
    }
  };

  const removeFromQueue = (id) => {
    setUploadQueue(prev => prev.filter(item => item.id !== id));
  };

  return (
    <div className="w-full">
      <div className="flex items-center mb-4">
        <h3 className="text-xl font-semibold text-slate-800">{title}</h3>
        <TooltipProvider>
          <Tooltip>
            <TooltipTrigger asChild>
              <HelpCircle className="w-4 h-4 ml-2 text-slate-400 cursor-pointer" />
            </TooltipTrigger>
            <TooltipContent>
              <p>{description}</p>
            </TooltipContent>
          </Tooltip>
        </TooltipProvider>
      </div>

      <div
        className={`border-2 border-dashed rounded-xl p-6 text-center transition-all duration-200 ${
          dragActive ? 'border-blue-400 bg-blue-50' : 'border-slate-200 bg-slate-50/50 hover:border-slate-300'
        }`}
        onDragEnter={handleDrag}
        onDragLeave={handleDrag}
        onDragOver={handleDrag}
        onDrop={handleDrop}
      >
        <input
          ref={fileInputRef}
          type="file"
          multiple
          accept="image/png,image/jpeg"
          onChange={handleFileInput}
          className="hidden"
        />
        <div className="w-12 h-12 mx-auto mb-3 bg-white rounded-full flex items-center justify-center border">
          <Upload className="w-6 h-6 text-slate-500" />
        </div>
        <p className="text-slate-600 mb-2 font-medium">拖拽文件到这里</p>
        <p className="text-xs text-slate-400 mb-4">支持PNG, JPG, JPEG格式, 不超过200MB</p>
        <Button
          onClick={() => fileInputRef.current.click()}
          variant="outline"
          className="bg-white shadow-sm"
        >
          浏览文件
        </Button>
      </div>

      <AnimatePresence>
        {uploadQueue.length > 0 && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            className="mt-4 space-y-2 max-h-60 overflow-y-auto pr-2"
          >
            {uploadQueue.map((item) => (
              <motion.div
                key={item.id}
                layout
                initial={{ opacity: 0, y: -10 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, x: -20 }}
                className="flex items-center justify-between p-2 bg-white rounded-lg border border-slate-200 shadow-sm"
              >
                <div className="flex items-center gap-2 overflow-hidden">
                  <Image className="w-5 h-5 text-slate-500 flex-shrink-0" />
                  <p className="font-medium text-sm text-slate-700 truncate" title={item.file.name}>{item.file.name}</p>
                </div>
                <div className="flex items-center gap-2 flex-shrink-0">
                  {item.status === 'pending' && <Badge variant="outline">等待中</Badge>}
                  {item.status === 'uploading' && <Loader2 className="w-4 h-4 text-blue-500 animate-spin" />}
                  {item.status === 'completed' && <Check className="w-4 h-4 text-green-500" />}
                  {item.status === 'error' && <Badge variant="destructive">{item.error}</Badge>}
                  <Button variant="ghost" size="icon" className="w-6 h-6 rounded-full" onClick={() => removeFromQueue(item.id)}>
                    <X className="w-3 h-3 text-slate-400" />
                  </Button>
                </div>
              </motion.div>
            ))}
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}
