"use client";

import { useRef, useState } from "react";
import Image from "next/image";

interface LogoUploaderProps {
  label?: string;
  value?: string | null;
  onChange?: (file: File, preview: string) => void;
  accept?: string[];
  maxSizeMB?: number;
  height?: string;
}

export default function LogoUploader({
  label = "Logo Upload",
  value = null,
  onChange,
  accept = ["image/png", "image/jpeg", "image/jpg", "image/gif"],
  maxSizeMB = 5,
  height = "h-48 2xl:h-60",
}: LogoUploaderProps) {
  const [isDragging, setIsDragging] = useState(false);
  const [error, setError] = useState<string>("");

  const fileInputRef = useRef<HTMLInputElement>(null);

  const handleFile = (file: File) => {
    if (!accept.includes(file.type)) {
      setError(
        `Only ${accept
          .map((type) => type.split("/")[1].toUpperCase())
          .join(", ")} files are allowed`,
      );
      return;
    }

    if (file.size > maxSizeMB * 1024 * 1024) {
      setError(`Maximum file size is ${maxSizeMB}MB`);
      return;
    }

    const reader = new FileReader();

    reader.onloadend = () => {
      onChange?.(file, reader.result as string);
    };

    reader.readAsDataURL(file);
  };

  const handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];

    if (file) {
      handleFile(file);
    }
  };

  const handleDrop = (event: React.DragEvent<HTMLDivElement>) => {
    event.preventDefault();
    setIsDragging(false);

    const file = event.dataTransfer.files?.[0];

    if (file) {
      handleFile(file);
    }
  };

  return (
    <div>
      <label className="mb-2 block text-sm font-medium text-table-text">
        {label}
      </label>

      <input
        ref={fileInputRef}
        type="file"
        accept={accept.join(",")}
        className="hidden"
        onChange={handleInputChange}
      />

      <div
        onClick={() => fileInputRef.current?.click()}
        onDragOver={(e) => {
          e.preventDefault();
          setIsDragging(true);
        }}
        onDragLeave={() => setIsDragging(false)}
        onDrop={handleDrop}
        className={`relative flex ${height} cursor-pointer items-center justify-center overflow-hidden rounded-2xl border border-dashed transition-all
          ${isDragging ? "border-primary bg-primary/5" : "border-[#E5DFFF]"}`}
      >
        {value ? (
          <>
            <img
              src={value}
              alt="Preview"
              className="object-contain p-4 w-full h-full"
            />

            <div className="absolute bottom-4 right-4 rounded-lg bg-black/70 px-3 py-2 text-xs text-white">
              Change Image
            </div>
          </>
        ) : (
          <div className="flex flex-col items-center p-4 text-center">
            <svg
              width="40"
              height="40"
              viewBox="0 0 24 24"
              fill="none"
              className="mb-4"
            >
              <path
                d="M19 3H5C3.9 3 3 3.9 3 5V19C3 20.1 3.9 21 5 21H19C20.1 21 21 20.1 21 19V5C21 3.9 20.1 3 19 3ZM19 19H5V5H19V19ZM8.5 13.5L11 16.51L14.5 12L19 18H5L8.5 13.5ZM8 9C8.83 9 9.5 8.33 9.5 7.5C9.5 6.67 8.83 6 8 6C7.17 6 6.5 6.67 6.5 7.5C6.5 8.33 7.17 9 8 9Z"
                fill="#9B5CF6"
              />
            </svg>

            <h3 className="text-sm xl:text-base 2xl:text-lg font-medium text-text">
              Upload a file or drag and drop
            </h3>

            <p className="mt-2 text-xs 2xl:text-sm text-gray-500">
              PNG, JPG, GIF up to {maxSizeMB}MB
            </p>
          </div>
        )}
      </div>

      {error && <div className="mt-2 text-sm text-red-500">{error}</div>}
    </div>
  );
}
