"use client"

import { useState } from "react"
import { SectionHeading } from "@/components/ui/section-heading"
import { Input } from "@/components/ui/input"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card"
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
import { Badge } from "@/components/ui/badge"

// Import comprehensive Lucide React icons
import {
  Home,
  Menu,
  Search,
  Settings,
  User,
  Users,
  UserPlus,
  UserMinus,
  UserCheck,
  UserX,
  ChevronLeft,
  ChevronRight,
  ChevronUp,
  ChevronDown,
  ChevronFirst,
  ChevronLast,
  ArrowLeft,
  ArrowRight,
  ArrowUp,
  ArrowDown,
  ArrowUpRight,
  ArrowDownRight,
  ArrowUpLeft,
  ArrowDownLeft,
  MoreHorizontal,
  MoreVertical,
  Plus,
  Minus,
  X,
  Check,
  CheckCircle,
  XCircle,
  Mail,
  MailOpen,
  Send,
  MessageCircle,
  MessageSquare,
  Phone,
  PhoneCall,
  PhoneIncoming,
  PhoneOutgoing,
  Bell,
  BellRing,
  BellOff,
  Share,
  Share2,
  Link,
  Link2,
  ExternalLink,
  ImageIcon,
  Images,
  Video,
  Music,
  File,
  FileText,
  FileImage,
  FileVideo,
  FileAudio,
  Folder,
  FolderOpen,
  FolderPlus,
  Download,
  Upload,
  Camera,
  Mic,
  MicOff,
  Edit,
  Edit2,
  Edit3,
  Trash,
  Trash2,
  Copy,
  Save,
  Undo,
  Redo,
  RefreshCw,
  RotateCcw,
  RotateCw,
  Shuffle,
  Repeat,
  Repeat1,
  AlertCircle,
  AlertTriangle,
  Info,
  HelpCircle,
  CheckCircle2,
  Loader,
  Loader2,
  Zap,
  Star,
  Heart,
  ThumbsUp,
  ThumbsDown,
  Flag,
  Bookmark,
  Lock,
  Unlock,
  Key,
  Shield,
  ShieldCheck,
  ShieldAlert,
  Eye,
  EyeOff,
  Fingerprint,
  Clock,
  Calendar,
  CalendarDays,
  Timer,
  AlarmClock,
  Hourglass,
  ShoppingCart,
  ShoppingBag,
  CreditCard,
  DollarSign,
  Receipt,
  Tag,
  Tags,
  Gift,
  Smartphone,
  Tablet,
  Laptop,
  Monitor,
  Tv,
  Headphones,
  Speaker,
  Wifi,
  WifiOff,
  Bluetooth,
  Usb,
  HardDrive,
  Server,
  Database,
  Cloud,
  CloudDownload,
  CloudUpload,
  Car,
  Truck,
  Plane,
  Train,
  Ship,
  Bike,
  Bus,
  Fuel,
  MapPin,
  Map,
  Navigation,
  Navigation2,
  Sun,
  Moon,
  CloudRain,
  CloudSnow,
  Umbrella,
  Rainbow,
  Users2,
  UserCircle,
  Crown,
  Award,
  Trophy,
  Target,
  Gamepad2,
  Dice1,
  Dice6,
  Briefcase,
  Building,
  Building2,
  Store,
  Factory,
  Banknote,
  TrendingUp,
  TrendingDown,
  BarChart,
  BarChart2,
  BarChart3,
  PieChart,
  LineChart,
  Activity,
  Wrench,
  Hammer,
  Paintbrush,
  Scissors,
  Ruler,
  Calculator,
  Compass,
  Flashlight,
  Magnet,
  Thermometer,
  Scale,
  Gauge,
  Coffee,
  Wine,
  Beer,
  Pizza,
  Apple,
  Cherry,
  Grape,
  IceCream,
  Cake,
  TreePine,
  Flower,
  Leaf,
  Bug,
  Fish,
  Bird,
  Cat,
  Dog,
  Rabbit,
  Turtle,
  Layout,
  LayoutGrid,
  LayoutList,
  Columns,
  Rows,
  Square,
  Circle,
  Triangle,
  AlignLeft,
  AlignCenter,
  AlignRight,
  AlignJustify,
  Bold,
  Italic,
  Underline,
  Code,
  Code2,
  Terminal,
  GitBranch,
  GitCommit,
  GitMerge,
  GitPullRequest,
  Package,
  Package2,
  Boxes,
  Component,
  Layers,
  Puzzle,
  MoveUp,
  MoveDown,
  MoveLeft,
  MoveRight,
  Move,
  Move3d,
  MousePointer,
  MousePointer2,
  Play,
  Pause,
  CircleStopIcon as Stop,
  SkipBack,
  SkipForward,
  FastForward,
  Rewind,
  Volume,
  Volume1,
  Volume2,
  VolumeX,
  Globe,
  Globe2,
  Battery,
  BatteryLow,
  Signal,
  Book,
  BookOpen,
  Library,
  GraduationCap,
  School,
  Stethoscope,
  Pill,
  Cross,
  Anchor,
  Feather,
  Sidebar,
  PanelLeft,
  PanelRight,
  PanelTop,
  PanelBottom,
  Maximize,
  Minimize,
  Maximize2,
  Minimize2,
  PictureInPicture,
  Scan,
  QrCode,
  Barcode,
  AtSign,
  Hash,
  Percent,
  Quote,
  Filter,
  FilterX,
  ArrowUpDown,
  ZoomIn,
  ZoomOut,
  Focus,
  Crosshair,
  Locate,
  LocateFixed,
  Verified,
  Pipette,
  Eraser,
  Pen,
  PenTool,
  Brush,
  Palette,
  Contrast,
  Lightbulb,
  Handshake,
  Stamp,
  Medal,
  Ribbon,
} from "lucide-react"

// Define categorized icon collections
const ICON_CATEGORIES = {
  "Navigation & UI": {
    icons: [
      "Home",
      "Menu",
      "Search",
      "Settings",
      "ChevronLeft",
      "ChevronRight",
      "ChevronUp",
      "ChevronDown",
      "ChevronFirst",
      "ChevronLast",
      "ArrowLeft",
      "ArrowRight",
      "ArrowUp",
      "ArrowDown",
      "ArrowUpRight",
      "ArrowDownRight",
      "ArrowUpLeft",
      "ArrowDownLeft",
      "MoreHorizontal",
      "MoreVertical",
      "Plus",
      "Minus",
      "X",
      "Check",
    ],
    color: "bg-blue-500/10 text-blue-700 dark:text-blue-300",
  },
  "Users & People": {
    icons: ["User", "Users", "UserPlus", "UserMinus", "UserCheck", "UserX", "Users2", "UserCircle", "Crown"],
    color: "bg-purple-500/10 text-purple-700 dark:text-purple-300",
  },
  Communication: {
    icons: [
      "Mail",
      "MailOpen",
      "Send",
      "MessageCircle",
      "MessageSquare",
      "Phone",
      "PhoneCall",
      "PhoneIncoming",
      "PhoneOutgoing",
      "Bell",
      "BellRing",
      "BellOff",
      "Share",
      "Share2",
      "Link",
      "Link2",
      "ExternalLink",
      "AtSign",
    ],
    color: "bg-green-500/10 text-green-700 dark:text-green-300",
  },
  "Media & Files": {
    icons: [
      "ImageIcon",
      "Images",
      "Video",
      "Music",
      "File",
      "FileText",
      "FileImage",
      "FileVideo",
      "FileAudio",
      "Folder",
      "FolderOpen",
      "FolderPlus",
      "Download",
      "Upload",
      "Camera",
      "Mic",
      "MicOff",
    ],
    color: "bg-orange-500/10 text-orange-700 dark:text-orange-300",
  },
  "Actions & Editing": {
    icons: [
      "Edit",
      "Edit2",
      "Edit3",
      "Trash",
      "Trash2",
      "Copy",
      "Save",
      "Undo",
      "Redo",
      "RefreshCw",
      "RotateCcw",
      "RotateCw",
      "Shuffle",
      "Repeat",
      "Repeat1",
    ],
    color: "bg-red-500/10 text-red-700 dark:text-red-300",
  },
  "Status & Feedback": {
    icons: [
      "AlertCircle",
      "AlertTriangle",
      "Info",
      "HelpCircle",
      "CheckCircle",
      "CheckCircle2",
      "XCircle",
      "Loader",
      "Loader2",
      "Zap",
      "Star",
      "Heart",
      "ThumbsUp",
      "ThumbsDown",
      "Flag",
      "Bookmark",
    ],
    color: "bg-yellow-500/10 text-yellow-700 dark:text-yellow-300",
  },
}

// Create a flat mapping of all icons
const LUCIDE_ICONS = {
  Home,
  Menu,
  Search,
  Settings,
  User,
  Users,
  UserPlus,
  UserMinus,
  UserCheck,
  UserX,
  ChevronLeft,
  ChevronRight,
  ChevronUp,
  ChevronDown,
  ChevronFirst,
  ChevronLast,
  ArrowLeft,
  ArrowRight,
  ArrowUp,
  ArrowDown,
  ArrowUpRight,
  ArrowDownRight,
  ArrowUpLeft,
  ArrowDownLeft,
  MoreHorizontal,
  MoreVertical,
  Plus,
  Minus,
  X,
  Check,
  CheckCircle,
  XCircle,
  Mail,
  MailOpen,
  Send,
  MessageCircle,
  MessageSquare,
  Phone,
  PhoneCall,
  PhoneIncoming,
  PhoneOutgoing,
  Bell,
  BellRing,
  BellOff,
  Share,
  Share2,
  Link,
  Link2,
  ExternalLink,
  ImageIcon,
  Images,
  Video,
  Music,
  File,
  FileText,
  FileImage,
  FileVideo,
  FileAudio,
  Folder,
  FolderOpen,
  FolderPlus,
  Download,
  Upload,
  Camera,
  Mic,
  MicOff,
  Edit,
  Edit2,
  Edit3,
  Trash,
  Trash2,
  Copy,
  Save,
  Undo,
  Redo,
  RefreshCw,
  RotateCcw,
  RotateCw,
  Shuffle,
  Repeat,
  Repeat1,
  AlertCircle,
  AlertTriangle,
  Info,
  HelpCircle,
  CheckCircle2,
  Loader,
  Loader2,
  Zap,
  Star,
  Heart,
  ThumbsUp,
  ThumbsDown,
  Flag,
  Bookmark,
  Lock,
  Unlock,
  Key,
  Shield,
  ShieldCheck,
  ShieldAlert,
  Eye,
  EyeOff,
  Fingerprint,
  Clock,
  Calendar,
  CalendarDays,
  Timer,
  AlarmClock,
  Hourglass,
  ShoppingCart,
  ShoppingBag,
  CreditCard,
  DollarSign,
  Receipt,
  Tag,
  Tags,
  Gift,
  Smartphone,
  Tablet,
  Laptop,
  Monitor,
  Tv,
  Headphones,
  Speaker,
  Wifi,
  WifiOff,
  Bluetooth,
  Usb,
  HardDrive,
  Server,
  Database,
  Cloud,
  CloudDownload,
  CloudUpload,
  Car,
  Truck,
  Plane,
  Train,
  Ship,
  Bike,
  Bus,
  Fuel,
  MapPin,
  Map,
  Navigation,
  Navigation2,
  Sun,
  Moon,
  CloudRain,
  CloudSnow,
  Umbrella,
  Rainbow,
  Users2,
  UserCircle,
  Crown,
  Award,
  Trophy,
  Target,
  Gamepad2,
  Dice1,
  Dice6,
  Briefcase,
  Building,
  Building2,
  Store,
  Factory,
  Banknote,
  TrendingUp,
  TrendingDown,
  BarChart,
  BarChart2,
  BarChart3,
  PieChart,
  LineChart,
  Activity,
  Wrench,
  Hammer,
  Paintbrush,
  Scissors,
  Ruler,
  Calculator,
  Compass,
  Flashlight,
  Magnet,
  Thermometer,
  Scale,
  Gauge,
  Coffee,
  Wine,
  Beer,
  Pizza,
  Apple,
  Cherry,
  Grape,
  IceCream,
  Cake,
  TreePine,
  Flower,
  Leaf,
  Bug,
  Fish,
  Bird,
  Cat,
  Dog,
  Rabbit,
  Turtle,
  Layout,
  LayoutGrid,
  LayoutList,
  Columns,
  Rows,
  Square,
  Circle,
  Triangle,
  AlignLeft,
  AlignCenter,
  AlignRight,
  AlignJustify,
  Bold,
  Italic,
  Underline,
  Code,
  Code2,
  Terminal,
  GitBranch,
  GitCommit,
  GitMerge,
  GitPullRequest,
  Package,
  Package2,
  Boxes,
  Component,
  Layers,
  Puzzle,
  MoveUp,
  MoveDown,
  MoveLeft,
  MoveRight,
  Move,
  Move3d,
  MousePointer,
  MousePointer2,
  Play,
  Pause,
  Stop,
  SkipBack,
  SkipForward,
  FastForward,
  Rewind,
  Volume,
  Volume1,
  Volume2,
  VolumeX,
  Globe,
  Globe2,
  Battery,
  BatteryLow,
  Signal,
  Book,
  BookOpen,
  Library,
  GraduationCap,
  School,
  Stethoscope,
  Pill,
  Cross,
  Anchor,
  Feather,
  Sidebar,
  PanelLeft,
  PanelRight,
  PanelTop,
  PanelBottom,
  Maximize,
  Minimize,
  Maximize2,
  Minimize2,
  PictureInPicture,
  Scan,
  QrCode,
  Barcode,
  AtSign,
  Hash,
  Percent,
  Quote,
  Filter,
  FilterX,
  ArrowUpDown,
  ZoomIn,
  ZoomOut,
  Focus,
  Crosshair,
  Locate,
  LocateFixed,
  Verified,
  Pipette,
  Eraser,
  Pen,
  PenTool,
  Brush,
  Palette,
  Contrast,
  Lightbulb,
  Handshake,
  Stamp,
  Medal,
  Ribbon,
}

// Available icon sizes
const ICON_SIZES = [
  { size: 16, label: "16px (sm)" },
  { size: 20, label: "20px (md)" },
  { size: 24, label: "24px (lg)" },
  { size: 32, label: "32px (xl)" },
  { size: 40, label: "40px (2xl)" },
  { size: 48, label: "48px (3xl)" },
]

// Convert PascalCase to kebab-case for display
const formatIconName = (name: string) => {
  return name
    .replace(/([A-Z])/g, "-$1")
    .toLowerCase()
    .replace(/^-/, "")
}

// Convert PascalCase to readable title
const formatIconTitle = (name: string) => {
  return name
    .replace(/([A-Z])/g, " $1")
    .replace(/^./, (str) => str.toUpperCase())
    .trim()
}

// Get all icon names for search
const getAllIconNames = () => {
  const allIcons: string[] = []
  Object.values(ICON_CATEGORIES).forEach((category) => {
    allIcons.push(...category.icons)
  })
  return allIcons
}

const allIconNames = getAllIconNames()

export function IconographySection() {
  const [searchTerm, setSearchTerm] = useState("")
  const [selectedIcon, setSelectedIcon] = useState<string | null>(null)
  const [selectedSize, setSelectedSize] = useState(24)
  const [copied, setCopied] = useState(false)

  // Filter icons based on search term
  const getFilteredCategories = () => {
    if (!searchTerm) return ICON_CATEGORIES

    const filtered: typeof ICON_CATEGORIES = {}
    Object.entries(ICON_CATEGORIES).forEach(([categoryName, category]) => {
      const matchingIcons = category.icons.filter(
        (iconName) =>
          iconName.toLowerCase().includes(searchTerm.toLowerCase()) ||
          formatIconName(iconName).includes(searchTerm.toLowerCase()) ||
          formatIconTitle(iconName).toLowerCase().includes(searchTerm.toLowerCase()),
      )

      if (matchingIcons.length > 0) {
        filtered[categoryName] = {
          ...category,
          icons: matchingIcons,
        }
      }
    })

    return filtered
  }

  const filteredCategories = getFilteredCategories()
  const totalFilteredIcons = Object.values(filteredCategories).reduce((sum, category) => sum + category.icons.length, 0)

  // Copy icon code to clipboard
  const copyIconCode = (iconName: string, size: number) => {
    const importCode = `import { ${iconName} } from "lucide-react"`
    const componentCode = `<${iconName} size={${size}} />`
    const fullCode = `${importCode}\n\n${componentCode}`

    navigator.clipboard.writeText(fullCode)
    setCopied(true)
    setTimeout(() => setCopied(false), 2000)
  }

  // Copy just the JSX
  const copyJSXOnly = (iconName: string, size: number) => {
    const jsxCode = `<${iconName} size={${size}} />`
    navigator.clipboard.writeText(jsxCode)
    setCopied(true)
    setTimeout(() => setCopied(false), 2000)
  }

  // Render icon component
  const renderIcon = (iconName: string, size = 24) => {
    const IconComponent = LUCIDE_ICONS[iconName as keyof typeof LUCIDE_ICONS]
    return IconComponent ? <IconComponent size={size} /> : null
  }

  return (
    <section id="iconography" className="mb-12">
      <SectionHeading
        title="Iconography"
        description="Comprehensive collection of Lucide React icons organized by category - beautiful, customizable SVG icons."
      />

      <div className="mb-8 mt-8">
        <div className="flex justify-between items-center mb-6">
          <div className="flex items-center gap-4">
            <Badge variant="secondary" className="text-sm">
              {totalFilteredIcons} icons available
            </Badge>
            <Badge variant="outline" className="text-sm">
              Lucide React v0.400+
            </Badge>
          </div>

          <div className="relative">
            <Input
              type="text"
              placeholder="Search icons..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="w-80"
            />
            <div className="absolute inset-y-0 right-3 flex items-center pointer-events-none">
              <Search className="h-4 w-4 text-muted-foreground" />
            </div>
          </div>
        </div>

        <Card>
          <CardHeader>
            <CardTitle>Lucide React Icons</CardTitle>
            <CardDescription>
              Click any icon to view sizes and copy the code. Icons are organized by category for easy browsing.
            </CardDescription>
          </CardHeader>
          <CardContent>
            {Object.keys(filteredCategories).length > 0 ? (
              <div className="space-y-8">
                {Object.entries(filteredCategories).map(([categoryName, category]) => (
                  <div key={categoryName}>
                    <div className="flex items-center gap-3 mb-4">
                      <h3 className="text-lg font-semibold">{categoryName}</h3>
                      <Badge variant="secondary" className={`text-xs ${category.color}`}>
                        {category.icons.length} icons
                      </Badge>
                    </div>

                    <div className="grid grid-cols-2 gap-4 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 2xl:grid-cols-8">
                      {category.icons.map((iconName) => (
                        <Popover key={iconName}>
                          <PopoverTrigger>
                            <div
                              className="flex flex-col items-center justify-center p-3 rounded-lg cursor-pointer hover:bg-secondary/50 transition-all duration-200 hover:scale-105 group border border-transparent hover:border-border"
                              onClick={() => setSelectedIcon(iconName)}
                            >
                              <div className="mb-2 p-2 rounded-md group-hover:bg-background transition-colors">
                                {renderIcon(iconName, 24)}
                              </div>
                              <div className="text-center">
                                <p className="text-xs font-medium text-foreground mb-1">{iconName}</p>
                                <p className="text-xs text-muted-foreground">{formatIconName(iconName)}</p>
                              </div>
                            </div>
                          </PopoverTrigger>
                          <PopoverContent className="w-80 z-50" align="center">
                            <div className="space-y-4">
                              <div className="text-center">
                                <div className="mb-2 p-3 rounded-lg bg-secondary/30 inline-block">
                                  {renderIcon(iconName, selectedSize)}
                                </div>
                                <h4 className="font-semibold">{iconName}</h4>
                                <p className="text-sm text-muted-foreground">{formatIconTitle(iconName)}</p>
                                <Badge variant="outline" className={`text-xs mt-2 ${category.color}`}>
                                  {categoryName}
                                </Badge>
                              </div>

                              <div>
                                <h5 className="text-sm font-medium mb-3">Available Sizes</h5>
                                <div className="grid grid-cols-3 gap-2">
                                  {ICON_SIZES.map(({ size, label }) => (
                                    <Button
                                      key={size}
                                      variant={selectedSize === size ? "default" : "outline"}
                                      size="sm"
                                      className="flex flex-col items-center gap-1 h-auto py-2"
                                      onClick={() => setSelectedSize(size)}
                                    >
                                      {renderIcon(iconName, size)}
                                      <span className="text-xs">{label}</span>
                                    </Button>
                                  ))}
                                </div>
                              </div>

                              <div>
                                <h5 className="text-sm font-medium mb-3">Usage</h5>
                                <div className="bg-secondary p-3 rounded-md mb-3 font-mono text-sm overflow-x-auto">
                                  <div className="text-muted-foreground mb-1">// Import</div>
                                  <div className="mb-2">{`import { ${iconName} } from "lucide-react"`}</div>
                                  <div className="text-muted-foreground mb-1">// Usage</div>
                                  <div>{`<${iconName} size={${selectedSize}} />`}</div>
                                </div>

                                <div className="flex gap-2">
                                  <Button
                                    variant="outline"
                                    size="sm"
                                    onClick={() => copyIconCode(iconName, selectedSize)}
                                    className="flex items-center gap-2 flex-1"
                                  >
                                    {copied ? <Check className="h-4 w-4" /> : <Copy className="h-4 w-4" />}
                                    {copied ? "Copied!" : "Copy Full Code"}
                                  </Button>
                                  <Button
                                    variant="outline"
                                    size="sm"
                                    onClick={() => copyJSXOnly(iconName, selectedSize)}
                                    className="flex items-center gap-2 flex-1"
                                  >
                                    <Code className="h-4 w-4" />
                                    JSX Only
                                  </Button>
                                </div>
                              </div>

                              <div className="pt-2 border-t">
                                <div className="flex items-center justify-between text-xs text-muted-foreground">
                                  <span>Lucide React</span>
                                  <span>MIT License</span>
                                </div>
                              </div>
                            </div>
                          </PopoverContent>
                        </Popover>
                      ))}
                    </div>
                  </div>
                ))}
              </div>
            ) : (
              <div className="text-center py-12">
                <Search className="h-12 w-12 text-muted-foreground mx-auto mb-4" />
                <p className="text-lg font-medium text-muted-foreground mb-2">No icons found</p>
                <p className="text-sm text-muted-foreground">
                  Try searching with different keywords like "arrow", "user", or "settings"
                </p>
              </div>
            )}
          </CardContent>
        </Card>
      </div>
    </section>
  )
}
