import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { useState, useCallback } from "react";
import { useDropzone } from "react-dropzone";
import { CameraIcon, X } from "lucide-react";
import Image from "next/image";

interface FileUploadProps {
  variant: "profile" | "image" | "multipleImages" | "pdf" | "button";
  maxFiles?: number;
  onFilesChange: (files: File[]) => void;
}

const FileUpload: React.FC<FileUploadProps> = ({
  variant,
  maxFiles,
  onFilesChange,
}) => {
  const [files, setFiles] = useState<File[]>([]);

  const onDrop = useCallback(
    (acceptedFiles: File[]) => {
      let updatedFiles = acceptedFiles;

      if (variant === "multipleImages") {
        // Append new files to the existing ones for multipleImages
        updatedFiles = [...files, ...acceptedFiles];

        // Limit to maxFiles if set
        if (maxFiles && updatedFiles.length > maxFiles) {
          updatedFiles = updatedFiles.slice(0, maxFiles);
        }
      } else if (maxFiles && acceptedFiles.length > maxFiles) {
        // Restrict number of files for other variants
        updatedFiles = acceptedFiles.slice(0, maxFiles);
      }

      setFiles(updatedFiles);
      onFilesChange(updatedFiles);
    },
    [files, maxFiles, onFilesChange, variant]
  );

  const { getRootProps, getInputProps, isDragActive } = useDropzone({
    onDrop,
    accept:
      variant === "pdf"
        ? { "application/pdf": [] }
        : variant === "profile" || variant === "image"
        ? { "image/*": [] }
        : undefined,
    maxFiles: variant === "multipleImages" ? maxFiles || 5 : 1,
  });

  const removeFile = (fileToRemove: File) => {
    const updatedFiles = files.filter((file) => file !== fileToRemove);
    setFiles(updatedFiles);
    onFilesChange(updatedFiles);
  };

  const renderPreview = () => {
    // Render Profile Preview (Only the first image, circular)
    if (variant === "profile" && files[0]) {
      return (
        <div className="relative w-24 h-24 rounded-full overflow-hidden">
          <Image
            width={500}
            height={500}
            src={URL.createObjectURL(files[0])}
            alt="Profile"
            className="w-full h-full object-cover"
          />
          <div className="absolute inset-0 bg-black bg-opacity-50 flex items-center justify-center">
            <span className="text-white text-sm">Change</span>
          </div>
        </div>
      );
    }

    // Render Multiple Image Preview (Grid layout) with "X" icon for removing
    if (variant === "multipleImages" && files.length > 0) {
      return (
        <div className="grid grid-cols-3 gap-2">
          {files.map((file) => (
            <div key={file.name} className="relative">
              <Image
                width={500}
                height={500}
                src={URL.createObjectURL(file)}
                alt="Preview"
                className="w-full h-24 object-cover rounded"
              />
              <button
                type="button"
                onClick={(e) => {
                  e.stopPropagation();
                  removeFile(file);
                }}
                className="absolute top-1 right-1 bg-black/50 text-white rounded-full p-1"
              >
                <X size={16} />
              </button>
            </div>
          ))}
        </div>
      );
    }

    // Render Single Image Preview (Not profile)
    if (variant === "image" && files[0]) {
      return (
        <div className="relative w-full h-24">
          <Image
            width={500}
            height={500}
            src={URL.createObjectURL(files[0])}
            alt="Image Preview"
            className="w-full h-full object-cover rounded"
          />
          <button
            type="button"
            onClick={() => removeFile(files[0])}
            className="absolute top-1 right-1 bg-red-500 text-white rounded-full p-1"
          >
            <X size={16} />
          </button>
        </div>
      );
    }

    // No preview for PDF and Button variants
    return null;
  };

  const renderPlaceholder = () => {
    if (variant === "profile") {
      return (
        <div className="w-24 h-24 rounded-full border-2 border-dashed flex items-center justify-center">
          <span className="text-gray-400">
            <CameraIcon className="" size={24} />
          </span>
        </div>
      );
    } else if (variant === "pdf") {
      return (
        <>
          <p className="text-neutral-700">Upload PDF</p>
          <p className="text-neutral-600 text-sm">
            Drag and drop or click to upload
          </p>
        </>
      );
    } else if (variant === "image") {
      return (
        <>
          <p className="text-neutral-700">Upload Image</p>
          <p className="text-neutral-600 text-sm">
            Drag and drop or click to upload
          </p>
        </>
      );
    } else if (variant === "multipleImages") {
      return (
        <>
          <p className="text-neutral-700">Upload Images</p>
          <p className="text-neutral-600 text-sm">
            Drag and drop or click to upload
          </p>
        </>
      );
    }

    return null;
  };

  return (
    <div>
      {variant !== "button" ? (
        <div
          {...getRootProps()}
          className={cn(
            // Conditionally apply border and padding for non-profile variants
            variant !== "profile"
              ? "border-2 border-dashed p-4 text-center cursor-pointer rounded"
              : "cursor-pointer",
            isDragActive ? "border-blue-500" : ""
          )}
        >
          <input {...getInputProps()} />
          {renderPreview() || renderPlaceholder()}
        </div>
      ) : (
        <Button onClick={getRootProps().onClick} className="w-full">
          Upload
        </Button>
      )}
    </div>
  );
};

export default FileUpload;
