import { faImage, faSpinner, faTimes } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import Image from "next/image";
import type React from "react";
import { useRef, useState } from "react";

interface ImageUploadProps {
  onImageUpload: (file: File | File[]) => Promise<void>;
  onImageDelete?: () => Promise<void>;
  currentImage?: string | null;
  multiple?: boolean;
  className?: string;
  disabled?: boolean;
  accept?: string;
  maxSize?: number; // in MB
}

export default function ImageUpload({
  onImageUpload,
  onImageDelete,
  currentImage,
  multiple = false,
  className = "",
  disabled = false,
  accept = "image/*",
  maxSize = 1024, // 1GB in MB
}: ImageUploadProps) {
  const [isUploading, setIsUploading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = e.target.files;
    if (!files || files.length === 0) return;

    setError(null);
    setIsUploading(true);

    try {
      if (multiple) {
        await onImageUpload(Array.from(files));
      } else {
        const file = files[0];

        // Validate file size
        if (file.size > maxSize * 1024 * 1024) {
          throw new Error(`File size must be less than ${maxSize}MB`);
        }

        // Log file details for debugging
        console.log("File details:", {
          name: file.name,
          type: file.type,
          size: file.size,
          lastModified: file.lastModified,
        });

        await onImageUpload(file);
      }

      // Reset file input
      if (fileInputRef.current) {
        fileInputRef.current.value = "";
      }
    } catch (err) {
      console.error("Upload error:", err);
      setError(err instanceof Error ? err.message : "Failed to upload image. Please try again.");
    } finally {
      setIsUploading(false);
    }
  };

  const handleDelete = async () => {
    if (!onImageDelete) return;

    try {
      await onImageDelete();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to delete image");
    }
  };

  return (
    <div className={`space-y-4 ${className}`}>
      <div className="relative">
        {currentImage ? (
          <div className="relative group">
            <Image
              src={typeof currentImage === "string" ? currentImage.replace("/uploads/", "/api/uploads/") : ""}
              alt="Uploaded preview"
              width={384}
              height={192}
              className="w-full h-48 object-cover rounded-lg"
            />
            {onImageDelete && (
              <button
                onClick={handleDelete}
                className="absolute top-2 right-2 inline-flex h-8 w-8 items-center justify-center rounded-md bg-slate-900/80 text-slate-200 opacity-0 backdrop-blur-sm transition-opacity hover:bg-rose-500 hover:text-white group-hover:opacity-100"
                disabled={disabled || isUploading}
                aria-label="Remove image"
              >
                <FontAwesomeIcon icon={faTimes} />
              </button>
            )}
          </div>
        ) : (
          <div className="flex h-48 w-full items-center justify-center rounded-lg border-2 border-dashed border-slate-800 bg-slate-950">
            <FontAwesomeIcon icon={faImage} className="text-3xl text-slate-600" />
          </div>
        )}
        <input
          ref={fileInputRef}
          type="file"
          accept={accept}
          multiple={multiple}
          onChange={handleFileChange}
          disabled={disabled || isUploading}
          className="hidden"
        />
        <button
          type="button"
          onClick={() => fileInputRef.current?.click()}
          disabled={disabled || isUploading}
          className="mt-3 inline-flex items-center justify-center gap-2 rounded-lg border border-slate-700 bg-slate-800 px-4 py-2 text-sm font-medium text-slate-100 transition-colors hover:border-slate-600 hover:bg-slate-700 focus:outline-none focus:ring-2 focus:ring-indigo-500/60 disabled:cursor-not-allowed disabled:opacity-50"
        >
          {currentImage
            ? multiple
              ? "Change images"
              : "Change image"
            : multiple
              ? "Select images"
              : "Select image"}
        </button>
      </div>
      <div className="space-y-2">
        {isUploading && (
          <div className="flex items-center text-sm text-slate-400">
            <FontAwesomeIcon icon={faSpinner} spin className="mr-2 text-indigo-400" />
            Uploading...
          </div>
        )}
        {error && <div className="text-sm text-rose-400">{error}</div>}
      </div>
    </div>
  );
}
