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

// ── Shared option sets ──────────────────────────────────────────────

const ORIENTATION_ALL = [
  { value: "", label: "All" },
  { value: "landscape", label: "Landscape" },
  { value: "portrait", label: "Portrait" },
  { value: "square", label: "Square" },
];

const OPENVERSE_ORIENTATION = [
  { value: "", label: "All" },
  { value: "square", label: "Square" },
  { value: "tall", label: "Tall" },
  { value: "wide", label: "Wide" },
];

const PIXABAY_ORIENTATION = [
  { value: "", label: "All" },
  { value: "horizontal", label: "Horizontal" },
  { value: "vertical", label: "Vertical" },
];

// ── Pexels-specific ────────────────────────────────────────────────

const PEXELS_COLOR = [
  { value: "", label: "All", hex: null },
  { value: "red", label: "Red", hex: "#ef4444" },
  { value: "orange", label: "Orange", hex: "#f97316" },
  { value: "yellow", label: "Yellow", hex: "#eab308" },
  { value: "green", label: "Green", hex: "#22c55e" },
  { value: "turquoise", label: "Turquoise", hex: "#14b8a6" },
  { value: "blue", label: "Blue", hex: "#3b82f6" },
  { value: "violet", label: "Violet", hex: "#a78bfa" },
  { value: "pink", label: "Pink", hex: "#ec4899" },
  { value: "brown", label: "Brown", hex: "#92400e" },
  { value: "black", label: "Black", hex: "#1f2937" },
  { value: "gray", label: "Gray", hex: "#6b7280" },
  { value: "white", label: "White", hex: "#f3f4f6" },
];

// ── Pixabay-specific ────────────────────────────────────────────────

const PIXABAY_ORDER = [
  { value: "popular", label: "Popular" },
  { value: "latest", label: "Latest" },
];

const PIXABAY_TYPE = [
  { value: "", label: "All" },
  { value: "photo", label: "Photo" },
  { value: "illustration", label: "Illustration" },
  { value: "vector", label: "Vector" },
];

const PIXABAY_CATEGORY = [
  { value: "", label: "All" },
  { value: "backgrounds", label: "Backgrounds" },
  { value: "fashion", label: "Fashion" },
  { value: "nature", label: "Nature" },
  { value: "science", label: "Science" },
  { value: "education", label: "Education" },
  { value: "feelings", label: "Feelings" },
  { value: "health", label: "Health" },
  { value: "people", label: "People" },
  { value: "religion", label: "Religion" },
  { value: "places", label: "Places" },
  { value: "animals", label: "Animals" },
  { value: "industry", label: "Industry" },
  { value: "computer", label: "Computer" },
  { value: "food", label: "Food" },
  { value: "sports", label: "Sports" },
  { value: "transportation", label: "Transportation" },
  { value: "travel", label: "Travel" },
  { value: "buildings", label: "Buildings" },
  { value: "business", label: "Business" },
  { value: "music", label: "Music" },
];

const PIXABAY_COLOR = [
  { value: "", label: "All", hex: null },
  { value: "grayscale", label: "Grayscale", hex: "#9ca3af" },
  { value: "red", label: "Red", hex: "#ef4444" },
  { value: "orange", label: "Orange", hex: "#f97316" },
  { value: "yellow", label: "Yellow", hex: "#eab308" },
  { value: "green", label: "Green", hex: "#22c55e" },
  { value: "turquoise", label: "Turquoise", hex: "#14b8a6" },
  { value: "blue", label: "Blue", hex: "#3b82f6" },
  { value: "lilac", label: "Lilac", hex: "#a78bfa" },
  { value: "pink", label: "Pink", hex: "#ec4899" },
  { value: "white", label: "White", hex: "#f3f4f6" },
  { value: "gray", label: "Gray", hex: "#6b7280" },
  { value: "black", label: "Black", hex: "#1f2937" },
  { value: "brown", label: "Brown", hex: "#92400e" },
  { value: "transparent", label: "Transparent", hex: null },
];

// ── Unsplash-specific ───────────────────────────────────────────────

const UNSPLASH_ORDER = [
  { value: "latest", label: "Latest" },
  { value: "relevant", label: "Relevant" },
];

// ── Openverse-specific ──────────────────────────────────────────────

const OPENVERSE_SOURCE = [
  { value: "", label: "All" },
  { value: "wordpress", label: "WordPress" },
  { value: "nasa", label: "Nasa" },
  { value: "spacex", label: "SpaceX" },
  { value: "wikimedia", label: "Wikimedia" },
  { value: "museum-victoria", label: "Museum Victoria" },
  { value: "met", label: "Met Museum" },
  { value: "rawpixel", label: "Rawpixel" },
  { value: "europeana", label: "Europeana" },
  { value: "bio_diversity", label: "Biodiversity Heritage" },
  { value: "smithsonian", label: "Smithsonian" },
  { value: "clevelandmuseum", label: "Cleveland Museum" },
  { value: "brooklynmuseum", label: "Brooklyn Museum" },
];

// ── Giphy-specific ──────────────────────────────────────────────────

const GIPHY_RATING = [
  { value: "g", label: "G" },
  { value: "pg", label: "PG" },
  { value: "pg-13", label: "PG-13" },
  { value: "r", label: "R" },
];

// ── Wikimedia-specific ──────────────────────────────────────────────

const WIKIMEDIA_MEDIA_TYPE = [
  { value: "", label: "All" },
  { value: "image", label: "Image" },
  { value: "vector", label: "Vector" },
];

const WIKIMEDIA_SORT = [
  { value: "relevance", label: "Relevance" },
  { value: "newest", label: "Newest" },
  { value: "oldest", label: "Oldest" },
];

// ── Per-provider filter definitions ─────────────────────────────────
// Each entry: { key, label, options, type? }
// type: "dropdown" (default) | "color"

const PROVIDER_FILTER_DEFS = {
  global: [],
  openverse: [
    { key: "source", label: "Source", options: OPENVERSE_SOURCE },
    { key: "orientation", label: "Orientation", options: OPENVERSE_ORIENTATION },
  ],
  unsplash: [
    { key: "order", label: "Order", options: UNSPLASH_ORDER },
  ],
  pixabay: [
    { key: "order", label: "Order", options: PIXABAY_ORDER },
    { key: "imageType", label: "Type", options: PIXABAY_TYPE },
    { key: "category", label: "Category", options: PIXABAY_CATEGORY },
    { key: "color", label: "Colors", options: PIXABAY_COLOR, type: "color" },
    { key: "orientation", label: "Orientation", options: PIXABAY_ORIENTATION },
  ],
  pexels: [
    { key: "orientation", label: "Orientation", options: ORIENTATION_ALL },
    { key: "color", label: "Colors", options: PEXELS_COLOR, type: "color" },
  ],
  giphy: [
    { key: "rating", label: "Rating", options: GIPHY_RATING },
  ],
  wikimedia: [
    { key: "mediaType", label: "Media Type", options: WIKIMEDIA_MEDIA_TYPE },
    { key: "sort", label: "Sort", options: WIKIMEDIA_SORT },
  ],
  openai: [],
  gemini: [],
};

// ── Dropdown component (like the competitor screenshots) ────────────

function FilterDropdown({ label, value, options, onChange, type }) {
  const selected = options.find((o) => o.value === value) || options[0];

  if (type === "color") {
    return (
      <div className="relative inline-flex items-center gap-1.5">
        <span className="text-xs font-medium text-gray-500">{label}</span>
        <div className="relative inline-flex items-center bg-white border border-gray-200 rounded-md hover:border-gray-300 transition-colors h-9">
          {selected.hex && (
            <div
              className="absolute left-2.5 w-3.5 h-3.5 rounded-full ring-1 ring-gray-300 pointer-events-none"
              style={{
                backgroundColor: selected.hex,
                border: selected.value === "white" ? "1px solid #d1d5db" : "none",
              }}
            />
          )}
          <select
            aria-label={label}
            value={value}
            onChange={(e) => onChange(e.target.value)}
            className="appearance-none bg-transparent text-sm font-medium text-gray-700 cursor-pointer focus:outline-none focus:ring-0 border-0 pr-7 py-2 h-9 min-h-0"
            style={{
              paddingLeft: selected.hex ? "2rem" : "0.625rem",
              backgroundImage:
                'url("data:image/svg+xml,%3csvg xmlns=\'http://www.w3.org/2000/svg\' fill=\'none\' viewBox=\'0 0 20 20\'%3e%3cpath stroke=\'%236b7280\' stroke-linecap=\'round\' stroke-linejoin=\'round\' stroke-width=\'1.5\' d=\'M6 8l4 4 4-4\'/%3e%3c/svg%3e")',
              backgroundPosition: "right 0.25rem center",
              backgroundRepeat: "no-repeat",
              backgroundSize: "1.25em 1.25em",
            }}
          >
            {options.map((opt) => (
              <option key={opt.value} value={opt.value}>
                {opt.label}
              </option>
            ))}
          </select>
        </div>
      </div>
    );
  }

  // Standard dropdown with label prefix
  return (
    <div className="relative inline-flex items-center gap-1.5">
      <span className="text-xs font-medium text-gray-500">{label}</span>
      <div className="relative inline-flex items-center bg-white border border-gray-200 rounded-md hover:border-gray-300 transition-colors h-9">
        <select
          aria-label={label}
          value={value}
          onChange={(e) => onChange(e.target.value)}
          className="appearance-none bg-transparent text-sm font-medium text-gray-800 cursor-pointer focus:outline-none focus:ring-0 border-0 pl-2.5 pr-7 py-2 h-9 min-h-0"
          style={{
            backgroundImage:
              'url("data:image/svg+xml,%3csvg xmlns=\'http://www.w3.org/2000/svg\' fill=\'none\' viewBox=\'0 0 20 20\'%3e%3cpath stroke=\'%236b7280\' stroke-linecap=\'round\' stroke-linejoin=\'round\' stroke-width=\'1.5\' d=\'M6 8l4 4 4-4\'/%3e%3c/svg%3e")',
            backgroundPosition: "right 0.25rem center",
            backgroundRepeat: "no-repeat",
            backgroundSize: "1.25em 1.25em",
          }}
        >
          {options.map((opt) => (
            <option key={opt.value} value={opt.value}>
              {opt.label}
            </option>
          ))}
        </select>
      </div>
    </div>
  );
}

// ── Main FilterBar ──────────────────────────────────────────────────

function FilterBar({ providerId, className = "" }) {
  const { getFilters, setFilter } = useGenerator();
  const filters = getFilters(providerId);
  const defs = PROVIDER_FILTER_DEFS[providerId] || [];

  if (defs.length === 0) return null;

  return (
    <div
      className={`flex flex-wrap items-center gap-3 sm:gap-4 ${className}`}
      role="group"
      aria-label="Filters"
    >
      {defs.map((def) => (
        <FilterDropdown
          key={def.key}
          label={def.label}
          value={filters[def.key] || def.options[0]?.value || ""}
          options={def.options}
          onChange={(val) => setFilter(providerId, def.key, val)}
          type={def.type}
        />
      ))}
    </div>
  );
}

export default memo(FilterBar);
