import React, { useState, memo } from "react";
import { useGenerator } from "../../context/GeneratorContext";
import { useUpload } from "../../context/UploadContext";

function SelectionToolbar({ currentImages = [], providerId = null, inline = false }) {
  const { getSelectedCount, clearSelection, setSelectionMode, getSelectedUrls, getSelectedItemsData, toggleFavorite, selectAll } = useGenerator();
  const { uploadImages, uploading } = useUpload();
  const [importing, setImporting] = useState(false);

  const count = getSelectedCount();
  const show = count > 0 || currentImages.length > 0;

  const handleImportAll = async () => {
    const items = getSelectedItemsData();
    if (items.length === 0) return;
    // Build items with url and title for proper naming on import
    const importItems = items
      .filter((item) => item.importUrl)
      .map((item) => ({ url: item.importUrl, title: item.imageAlt || "", author: item.author?.name || "" }));
    if (importItems.length === 0) return;
    setImporting(true);
    try {
      await uploadImages(importItems);
      clearSelection();
    } finally {
      setImporting(false);
    }
  };

  const handleFavoriteAll = () => {
    const items = getSelectedItemsData();
    items.forEach(({ providerId, imageId, ...data }) => {
      toggleFavorite(providerId, imageId, data);
    });
    clearSelection();
  };

  const handleClear = () => {
    clearSelection();
    setSelectionMode(false);
  };

  const handleSelectAll = () => {
    if (!providerId || !currentImages.length) return;
    const imageData = {};
    currentImages.forEach(img => {
      const key = `${providerId}:${img.imageId}`;
      imageData[key] = {
        importUrl: img.importUrl,
        imageSrc: img.imageSrc,
        imageAlt: img.imageAlt,
        author: img.author,
        previewUrl: img.previewUrl
      };
    });
    selectAll(providerId, currentImages.map(img => img.imageId), imageData);
  };

  if (!show && !currentImages.length) return null;

  const urls = getSelectedUrls();
  const canImport = urls.length > 0 && !uploading && !importing;
  const isFavoritesTab = providerId === "favorites";

  // Only show when there are selected images
  if (count === 0) return null;

  return (
    <div
      className={inline 
        ? "px-6 py-4 border-t border-gray-200 flex flex-wrap items-center gap-3" 
        : "fixed bottom-0 left-0 right-0 z-50 flex justify-center border-t border-gray-200 bg-white py-4 shadow-lg transition-transform duration-300"
      }
      role="toolbar"
      aria-label="Selection actions"
    >
      <div className={inline 
        ? "flex flex-wrap items-center gap-3 w-full"
        : "flex max-w-5xl flex-wrap items-center justify-center gap-4 px-4"
      }>
        <span className="text-xs sm:text-sm font-medium text-gray-700">
          {count} image{count !== 1 ? "s" : ""} selected
        </span>
        <div className="flex flex-wrap items-center gap-2">
          <button
            type="button"
            onClick={handleImportAll}
            disabled={!canImport}
            className="rounded-md border border-gray-800 bg-gray-800 px-3 sm:px-4 h-9 text-xs sm:text-sm font-medium text-white hover:bg-gray-900 focus:outline-none focus:ring-2 focus:ring-gray-600 disabled:opacity-50"
          >
            {importing ? "Importing..." : "Import All"}
          </button>
          <button
            type="button"
            onClick={handleFavoriteAll}
            className="rounded-md border border-gray-200 bg-white px-3 sm:px-4 h-9 text-xs sm:text-sm font-medium text-gray-700 hover:bg-gray-50 hover:border-gray-300 focus:outline-none focus:ring-2 focus:ring-gray-600"
          >
            {isFavoritesTab ? "Unfavorite All" : "Favorite All"}
          </button>
          <button
            type="button"
            onClick={handleClear}
            className="rounded-md border border-gray-200 bg-white px-3 sm:px-4 h-9 text-xs sm:text-sm font-medium text-gray-700 hover:bg-gray-50 hover:border-gray-300 focus:outline-none focus:ring-2 focus:ring-gray-600"
          >
            Clear
          </button>
        </div>
      </div>
    </div>
  );
}

export default memo(SelectionToolbar);
