// File: src/components/UIX/IconPicker/IconPicker.jsx
// UIX version - Icon picker component for selecting emojis or predefined icons
// Theme-aware with proper UIX component usage
import React, { useState, useCallback, useMemo } from "react";
import {
  XMarkIcon,
  FolderIcon,
  BriefcaseIcon,
  PhotoIcon,
  MusicalNoteIcon,
  VideoCameraIcon,
  DocumentTextIcon,
  ArchiveBoxIcon,
  StarIcon,
  HeartIcon,
  HomeIcon,
  AcademicCapIcon,
  CodeBracketIcon,
  CloudIcon,
  LockClosedIcon,
  GiftIcon,
  CalendarIcon,
  BookOpenIcon,
  CameraIcon,
  FilmIcon,
  GlobeAltIcon,
  MapPinIcon,
  ShoppingBagIcon,
  WrenchScrewdriverIcon,
  BanknotesIcon,
  BeakerIcon,
  BoltIcon,
  ChatBubbleLeftIcon,
  ClipboardDocumentIcon,
  CpuChipIcon,
  CubeIcon,
  FireIcon,
  FlagIcon,
  PaperAirplaneIcon,
  RocketLaunchIcon,
  SparklesIcon,
  TrophyIcon,
  UserGroupIcon,
} from "@heroicons/react/24/outline";
import { useUIXTheme } from "../themes/useUIXTheme";
import Button from "../Button/Button";
import Tabs from "../Tabs/Tabs";

// Predefined icons with their identifiers and labels
const PREDEFINED_ICONS = [
  { id: "briefcase", Icon: BriefcaseIcon, label: "Work" },
  { id: "photo", Icon: PhotoIcon, label: "Photos" },
  { id: "music", Icon: MusicalNoteIcon, label: "Music" },
  { id: "video", Icon: VideoCameraIcon, label: "Videos" },
  { id: "document", Icon: DocumentTextIcon, label: "Documents" },
  { id: "archive", Icon: ArchiveBoxIcon, label: "Archive" },
  { id: "star", Icon: StarIcon, label: "Favorites" },
  { id: "heart", Icon: HeartIcon, label: "Personal" },
  { id: "home", Icon: HomeIcon, label: "Home" },
  { id: "academic", Icon: AcademicCapIcon, label: "School" },
  { id: "code", Icon: CodeBracketIcon, label: "Code" },
  { id: "cloud", Icon: CloudIcon, label: "Cloud" },
  { id: "lock", Icon: LockClosedIcon, label: "Private" },
  { id: "gift", Icon: GiftIcon, label: "Gifts" },
  { id: "calendar", Icon: CalendarIcon, label: "Events" },
  { id: "book", Icon: BookOpenIcon, label: "Books" },
  { id: "camera", Icon: CameraIcon, label: "Camera" },
  { id: "film", Icon: FilmIcon, label: "Movies" },
  { id: "globe", Icon: GlobeAltIcon, label: "Travel" },
  { id: "map", Icon: MapPinIcon, label: "Places" },
  { id: "shopping", Icon: ShoppingBagIcon, label: "Shopping" },
  { id: "tools", Icon: WrenchScrewdriverIcon, label: "Projects" },
  { id: "money", Icon: BanknotesIcon, label: "Finance" },
  { id: "science", Icon: BeakerIcon, label: "Science" },
  { id: "energy", Icon: BoltIcon, label: "Energy" },
  { id: "chat", Icon: ChatBubbleLeftIcon, label: "Messages" },
  { id: "clipboard", Icon: ClipboardDocumentIcon, label: "Notes" },
  { id: "tech", Icon: CpuChipIcon, label: "Tech" },
  { id: "cube", Icon: CubeIcon, label: "3D" },
  { id: "fire", Icon: FireIcon, label: "Hot" },
  { id: "flag", Icon: FlagIcon, label: "Goals" },
  { id: "plane", Icon: PaperAirplaneIcon, label: "Sent" },
  { id: "rocket", Icon: RocketLaunchIcon, label: "Launch" },
  { id: "sparkles", Icon: SparklesIcon, label: "Magic" },
  { id: "trophy", Icon: TrophyIcon, label: "Awards" },
  { id: "group", Icon: UserGroupIcon, label: "Team" },
];

// Comprehensive emoji collection organized by logical categories
const EMOJI_CATEGORIES = {
  "Folders & Work": [
    "📁", "📂", "🗂️", "📑", "📄", "📃", "📋", "📝", "✏️", "🖊️",
    "📎", "📌", "🔖", "🏷️", "📰", "🗃️", "🗄️", "📦", "📥", "📤",
    "💼", "🏢", "🏛️", "🏦", "💰", "💵", "💳", "🧾", "📊", "📈",
    "📉", "💹", "🗓️", "📅", "⏰", "⌚", "🖥️", "💻", "⌨️", "🖨️",
  ],
  "Tech & Media": [
    "📱", "📲", "☎️", "📞", "📟", "📠", "🔌", "🔋", "💾", "💿",
    "📀", "🖱️", "🖲️", "🎮", "🕹️", "🛜", "📡", "📺", "📻", "🎙️",
    "📷", "📸", "📹", "🎥", "🎬", "🎞️", "📽️", "🎵", "🎶", "🎤",
    "🎧", "🎼", "🎹", "🎸", "🥁", "🎨", "🖼️", "🎭", "🎪", "🎠",
    "🔒", "🔓", "🔐", "🔑", "🗝️", "🛡️", "⚔️", "🔫", "🚨", "🚔",
    "👮", "🕵️", "🦺", "🧯", "🪖", "⛑️", "🔏", "👁️‍🗨️", "🛂",
    "💬", "💭", "🗨️", "🗯️", "📧", "📨", "📩", "📮", "📪", "📫",
    "📬", "📭", "✉️", "💌", "📯", "🔔", "🔕", "📢", "📣", "🗣️",
  ],
  "Education & Science": [
    "📚", "📖", "📕", "📗", "📘", "📙", "🎓", "🏫", "✍️", "📐",
    "📏", "🔬", "🔭", "🧪", "🧫", "🧬", "🔍", "🔎", "💡", "📡",
  ],
  "Home & Life": [
    "🏠", "🏡", "🏘️", "🛏️", "🛋️", "🪑", "🚿", "🛁", "🧹", "🧺",
    "👨‍👩‍👧‍👦", "👪", "❤️", "💕", "💝", "💖", "🧸", "🎁", "🎀", "🎈",
  ],
  "Health & Food": [
    "🏥", "💊", "💉", "🩺", "🩹", "🩼", "♿", "🧘", "🏃", "🚴",
    "🏋️", "🤸", "⚕️", "🩸", "🧠", "👁️", "🦷", "💪", "🧬", "🍎",
    "🍕", "🍔", "🍟", "🌮", "🌯", "🍜", "🍝", "🍣", "🍱", "🥗",
    "🍰", "🎂", "🧁", "🍩", "🍪", "☕", "🍵", "🥤", "🍷", "🍺",
  ],
  "Travel & Places": [
    "✈️", "🚀", "🛸", "🚁", "🚂", "🚗", "🚕", "🚌", "🚢", "⛵",
    "🗺️", "🧭", "🏖️", "🏔️", "🏕️", "🗽", "🗼", "🏰", "⛺", "🌍",
  ],
  "Sports & Hobbies": [
    "⚽", "🏀", "🏈", "⚾", "🎾", "🏐", "🏓", "🏸", "🎯", "🎱",
    "🎳", "🏆", "🥇", "🥈", "🥉", "🎲", "♟️", "🧩", "🎰", "🎮",
  ],
  "Nature & Animals": [
    "🌸", "🌺", "🌻", "🌹", "🌷", "🌴", "🌲", "🍀", "🌿", "🍃",
    "☀️", "🌙", "⭐", "🌈", "☁️", "🌧️", "❄️", "🔥", "💧", "🌊",
    "🐶", "🐱", "🐭", "🐹", "🐰", "🦊", "🐻", "🐼", "🐨", "🦁",
    "🐯", "🐮", "🐷", "🐸", "🐵", "🐔", "🐧", "🐦", "🦋", "🐝",
  ],
  "Symbols & Status": [
    "✅", "❌", "⭕", "❗", "❓", "💯", "🔴", "🟠", "🟡", "🟢",
    "🔵", "🟣", "⚫", "⚪", "🔶", "🔷", "💠", "🔘", "🏁", "🚩",
  ],
  "Time & Planning": [
    "⏰", "⏱️", "⏲️", "🕐", "🕑", "🕒", "🕓", "🕔", "🕕", "🕖",
    "📅", "📆", "🗓️", "⌛", "⏳", "🔜", "🔙", "🔚", "🔛", "🔝",
  ],
  "Celebration": [
    "🎉", "🎊", "🎂", "🎁", "🎀", "🎈", "🎄", "🎃", "🎆", "🎇",
    "✨", "💫", "🌟", "⭐", "🏅", "🎖️", "🏆", "🥳", "🎯", "🎪",
  ],
};

const IconPicker = ({ value, onChange, onClose, isOpen }) => {
  const { getThemeClasses } = useUIXTheme();
  const [activeTab, setActiveTab] = useState("emoji");
  const [activeEmojiCategory, setActiveEmojiCategory] = useState("Folders & Work");

  // Memoize category keys
  const categoryKeys = useMemo(() => Object.keys(EMOJI_CATEGORIES), []);

  // Memoize tabs configuration
  const tabsConfig = useMemo(() => [
    { id: "emoji", label: "Emoji" },
    { id: "icons", label: "Icons" },
  ], []);

  // Handlers
  const handleSelect = useCallback((iconValue) => {
    onChange(iconValue);
    onClose();
  }, [onChange, onClose]);

  const handleReset = useCallback(() => {
    onChange("");
    onClose();
  }, [onChange, onClose]);

  const handleTabChange = useCallback((tab) => {
    setActiveTab(tab);
  }, []);

  const handleCategoryChange = useCallback((category) => {
    setActiveEmojiCategory(category);
  }, []);

  // Handle backdrop click
  const handleBackdropClick = useCallback((e) => {
    if (e.target === e.currentTarget) {
      onClose();
    }
  }, [onClose]);

  // Handle escape key
  const handleKeyDown = useCallback((e) => {
    if (e.key === "Escape") {
      onClose();
    }
  }, [onClose]);

  if (!isOpen) return null;

  // Check if current value is an icon or emoji (with type safety)
  const safeValue = typeof value === 'string' ? value : '';
  const isIconSelected = safeValue.startsWith("icon:");
  const selectedIconId = isIconSelected ? safeValue.replace("icon:", "") : null;

  return (
    <div
      className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50"
      onClick={handleBackdropClick}
      onKeyDown={handleKeyDown}
      role="dialog"
      aria-modal="true"
      aria-labelledby="icon-picker-title"
    >
      <div className={`${getThemeClasses("bg-card")} rounded-xl shadow-xl w-full max-w-2xl lg:max-w-4xl xl:max-w-5xl max-h-[85vh] flex flex-col`}>
        {/* Header */}
        <div className={`flex items-center justify-between p-4 border-b ${getThemeClasses("border-secondary")}`}>
          <h3 id="icon-picker-title" className={`text-lg font-semibold ${getThemeClasses("text-primary")}`}>
            Choose Icon
          </h3>
          <Button
            onClick={onClose}
            variant="ghost"
            size="sm"
            aria-label="Close icon picker"
          >
            <XMarkIcon className="h-5 w-5" />
          </Button>
        </div>

        {/* Tabs */}
        <Tabs
          tabs={tabsConfig}
          activeTab={activeTab}
          onTabChange={handleTabChange}
          variant="underline"
          size="sm"
          fullWidth
        />

        {/* Content */}
        <div className="flex-1 overflow-y-auto p-4">
          {activeTab === "emoji" ? (
            <div className="flex gap-4">
              {/* Category Sidebar */}
              <div className={`w-44 flex-shrink-0 border-r ${getThemeClasses("border-secondary")} pr-4`}>
                <div className="sticky top-0 space-y-1 max-h-[60vh] overflow-y-auto">
                  {categoryKeys.map((category) => (
                    <Button
                      key={category}
                      onClick={() => handleCategoryChange(category)}
                      variant={activeEmojiCategory === category ? "ghost" : "ghost"}
                      size="sm"
                      className={`w-full justify-start text-xs ${
                        activeEmojiCategory === category
                          ? `${getThemeClasses("bg-accent-light")} ${getThemeClasses("text-accent")}`
                          : ""
                      }`}
                    >
                      {category}
                    </Button>
                  ))}
                </div>
              </div>

              {/* Emoji Grid */}
              <div className="flex-1">
                <h4 className={`text-sm font-medium ${getThemeClasses("text-primary")} mb-3`}>
                  {activeEmojiCategory}
                </h4>
                <div className="grid grid-cols-8 sm:grid-cols-10 lg:grid-cols-12 gap-1">
                  {EMOJI_CATEGORIES[activeEmojiCategory].map((emoji, index) => (
                    <Button
                      key={`${emoji}-${index}`}
                      onClick={() => handleSelect(emoji)}
                      variant="ghost"
                      size="sm"
                      className={`p-2 text-2xl ${
                        safeValue === emoji ? `${getThemeClasses("bg-accent-light")} ring-2 ${getThemeClasses("ring-accent")}` : ""
                      }`}
                      title={emoji}
                    >
                      {emoji}
                    </Button>
                  ))}
                </div>
              </div>
            </div>
          ) : (
            <div className="grid grid-cols-4 sm:grid-cols-6 lg:grid-cols-8 gap-2">
              {PREDEFINED_ICONS.map(({ id, Icon, label }) => (
                <Button
                  key={id}
                  onClick={() => handleSelect(`icon:${id}`)}
                  variant="ghost"
                  className={`flex flex-col items-center p-3 h-auto ${
                    selectedIconId === id ? `${getThemeClasses("bg-accent-light")} ring-2 ${getThemeClasses("ring-accent")}` : ""
                  }`}
                  title={label}
                >
                  <Icon className={`h-6 w-6 ${getThemeClasses("text-primary")}`} />
                  <span className={`text-xs ${getThemeClasses("text-secondary")} mt-1 truncate w-full text-center`}>
                    {label}
                  </span>
                </Button>
              ))}
            </div>
          )}
        </div>

        {/* Footer */}
        <div className={`flex items-center justify-between p-4 border-t ${getThemeClasses("border-secondary")} ${getThemeClasses("bg-muted")} rounded-b-xl`}>
          <Button
            onClick={handleReset}
            variant="ghost"
            size="sm"
            icon={FolderIcon}
          >
            Reset to Default
          </Button>
          <Button
            onClick={onClose}
            variant="secondary"
            size="sm"
          >
            Cancel
          </Button>
        </div>
      </div>
    </div>
  );
};

// Export the predefined icons map for use in CollectionIcon component
export const ICON_MAP = PREDEFINED_ICONS.reduce((acc, { id, Icon }) => {
  acc[id] = Icon;
  return acc;
}, {});

export default IconPicker;
