"use client";

import { useState, useCallback, useEffect } from "react";
import { useDropzone } from "react-dropzone";
import { Upload, X, FileText, CloudUpload } from "lucide-react";

interface WorkflowUploadSectionProps {
  onUpload: (files: File[]) => Promise<void>;
  isUploading: boolean;
  uploadProgress: number;
}

function formatFileSize(bytes: number): string {
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}

export function WorkflowUploadSection({
  onUpload,
  isUploading,
  uploadProgress,
}: WorkflowUploadSectionProps) {
  const [selectedFiles, setSelectedFiles] = useState<File[]>([]);
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    const timer = setTimeout(() => setMounted(true), 50);
    return () => clearTimeout(timer);
  }, []);

  const onDrop = useCallback((acceptedFiles: File[]) => {
    setSelectedFiles((prev) => [...prev, ...acceptedFiles]);
  }, []);

  const { getRootProps, getInputProps, isDragActive } = useDropzone({
    onDrop,
    accept: {
      "application/pdf": [".pdf"],
      "image/png": [".png"],
      "image/jpeg": [".jpg", ".jpeg"],
    },
    multiple: true,
    disabled: isUploading,
  });

  const removeFile = (index: number) => {
    setSelectedFiles((prev) => prev.filter((_, i) => i !== index));
  };

  const handleUpload = async () => {
    if (selectedFiles.length === 0) return;
    await onUpload(selectedFiles);
    setSelectedFiles([]);
  };

  return (
    <div
      className="space-y-4 transition-all duration-500 ease-out"
      style={{
        opacity: mounted ? 1 : 0,
        transform: mounted ? "translateY(0)" : "translateY(12px)",
      }}
    >
      <h3 className="text-sm font-semibold text-gray-700">Upload Documents</h3>

      {/* Drop zone */}
      <div
        {...getRootProps()}
        className={`relative border-2 border-dashed rounded-xl p-10 text-center cursor-pointer transition-all duration-300 overflow-hidden ${
          isDragActive
            ? "border-[#428B4D] bg-[#428B4D]/5 scale-[1.01]"
            : isUploading
            ? "border-gray-200 bg-gray-50/50 cursor-not-allowed"
            : "border-gray-300 bg-gray-50/30 hover:border-[#428B4D]/50 hover:bg-[#428B4D]/[0.02]"
        }`}
      >
        <input {...getInputProps()} />

        {/* Animated background glow on drag */}
        {isDragActive && (
          <div className="absolute inset-0 bg-gradient-to-br from-[#428B4D]/5 via-transparent to-[#428B4D]/10 animate-pulse" />
        )}

        <div className="relative z-10">
          <div
            className={`mx-auto mb-3 flex h-12 w-12 items-center justify-center rounded-full transition-all duration-300 ${
              isDragActive
                ? "bg-[#428B4D]/10 scale-110"
                : "bg-gray-100"
            }`}
          >
            <CloudUpload
              className={`h-6 w-6 transition-all duration-300 ${
                isDragActive
                  ? "text-[#428B4D] -translate-y-0.5"
                  : "text-gray-400"
              }`}
            />
          </div>
          {isDragActive ? (
            <p className="text-sm font-medium text-[#428B4D]">
              Drop files here...
            </p>
          ) : (
            <div>
              <p className="text-sm text-gray-600">
                Drag & drop files here, or{" "}
                <span className="text-[#428B4D] font-medium">click to select</span>
              </p>
              <p className="text-xs text-gray-400 mt-1">
                Supports PDF, PNG, JPG (multiple files)
              </p>
            </div>
          )}
        </div>
      </div>

      {/* Selected files list */}
      {selectedFiles.length > 0 && (
        <div className="space-y-2">
          <h4 className="text-xs font-medium text-gray-500">
            Selected Files ({selectedFiles.length})
          </h4>
          <div className="space-y-1.5 max-h-40 overflow-y-auto">
            {selectedFiles.map((file, idx) => (
              <div
                key={idx}
                className="flex items-center justify-between px-3 py-2 bg-white border border-gray-200/80 rounded-lg text-xs transition-all duration-300 ease-out hover:shadow-sm"
                style={{
                  opacity: 1,
                  animation: `fadeSlideIn 0.3s ease-out ${idx * 50}ms both`,
                }}
              >
                <div className="flex items-center gap-2.5">
                  <div className="flex h-7 w-7 items-center justify-center rounded-lg bg-[#428B4D]/10">
                    <FileText className="h-3.5 w-3.5 text-[#428B4D]" />
                  </div>
                  <div>
                    <span className="text-gray-700 font-medium truncate block max-w-[300px]">
                      {file.name}
                    </span>
                    <span className="text-gray-400 text-[10px]">
                      {formatFileSize(file.size)}
                    </span>
                  </div>
                </div>
                <button
                  onClick={(e) => {
                    e.stopPropagation();
                    removeFile(idx);
                  }}
                  className="flex h-6 w-6 items-center justify-center rounded-full text-gray-400 hover:bg-red-50 hover:text-red-500 transition-colors"
                  disabled={isUploading}
                >
                  <X className="h-3.5 w-3.5" />
                </button>
              </div>
            ))}
          </div>

          {/* Upload button + progress */}
          <div className="flex items-center gap-3 pt-1">
            <button
              onClick={handleUpload}
              disabled={isUploading || selectedFiles.length === 0}
              className="inline-flex items-center gap-2 px-5 py-2.5 text-xs font-semibold bg-[#428B4D] text-white rounded-lg hover:bg-[#357a3f] disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200 shadow-sm hover:shadow-md active:scale-[0.98]"
            >
              <Upload className="h-3.5 w-3.5" />
              {isUploading
                ? `Processing... ${uploadProgress}%`
                : `Upload & Process (${selectedFiles.length})`}
            </button>
          </div>

          {/* Progress bar */}
          {isUploading && (
            <div className="w-full bg-gray-100 rounded-full h-2 overflow-hidden">
              <div
                className="bg-gradient-to-r from-[#428B4D] to-[#5aad64] h-2 rounded-full transition-all duration-500 ease-out relative"
                style={{ width: `${uploadProgress}%` }}
              >
                <div className="absolute inset-0 bg-white/20 animate-pulse" />
              </div>
            </div>
          )}
        </div>
      )}

    </div>
  );
}
