"use client";

import { useState, useMemo } from "react";
import { Search } from "lucide-react";
import { Input } from "@/components/ui/input";
import { cn } from "@/lib/utils";
import { SECTOR_ICONS, SECTOR_ICON_CATEGORIES } from "@/lib/sectorIconMap";

interface SectorIconPickerProps {
  value: string;
  onChange: (key: string) => void;
}

export function SectorIconPicker({ value, onChange }: SectorIconPickerProps) {
  const [search, setSearch] = useState("");
  const [activeCategory, setActiveCategory] = useState<string>("All");

  const filtered = useMemo(() => {
    const q = search.toLowerCase().trim();
    return Object.entries(SECTOR_ICONS).filter(([key, entry]) => {
      const matchesCategory = activeCategory === "All" || entry.category === activeCategory;
      const matchesSearch =
        !q ||
        entry.label.toLowerCase().includes(q) ||
        entry.category.toLowerCase().includes(q) ||
        key.toLowerCase().includes(q);
      return matchesCategory && matchesSearch;
    });
  }, [search, activeCategory]);

  const selectedEntry = value ? SECTOR_ICONS[value] : null;

  return (
    <div className="space-y-2">
      {/* Search */}
      <div className="relative">
        <Search className="absolute left-2.5 top-2.5 h-3.5 w-3.5 text-muted-foreground" />
        <Input
          placeholder="Search icons..."
          className="pl-8 h-8 text-sm"
          value={search}
          onChange={(e) => setSearch(e.target.value)}
        />
      </div>

      {/* Category pills */}
      <div className="flex flex-wrap gap-1">
        {SECTOR_ICON_CATEGORIES.map((cat) => (
          <button
            key={cat}
            type="button"
            onClick={() => setActiveCategory(cat)}
            className={cn(
              "px-2 py-0.5 text-[11px] rounded-full border transition-colors",
              activeCategory === cat
                ? "bg-primary text-primary-foreground border-primary"
                : "border-border text-muted-foreground hover:bg-muted hover:text-foreground",
            )}
          >
            {cat}
          </button>
        ))}
      </div>

      {/* Icon grid */}
      <div className="h-56 overflow-y-auto rounded-md border bg-muted/20 p-1">
        {filtered.length > 0 ? (
          <div className="grid grid-cols-7 gap-0.5">
            {filtered.map(([key, entry]) => {
              const Icon = entry.component;
              return (
                <button
                  key={key}
                  type="button"
                  onClick={() => onChange(key)}
                  title={`${entry.label} (${entry.category})`}
                  className={cn(
                    "flex flex-col items-center justify-center gap-1 p-1.5 rounded text-[9px] leading-tight hover:bg-muted transition-colors min-h-[52px]",
                    value === key && "ring-2 ring-primary bg-primary/10 text-primary",
                  )}
                >
                  <Icon className="h-4 w-4 shrink-0" />
                  <span className="truncate w-full text-center">{entry.label}</span>
                </button>
              );
            })}
          </div>
        ) : (
          <div className="h-full flex items-center justify-center text-sm text-muted-foreground">
            No icons match your search.
          </div>
        )}
      </div>

      {/* Selected preview */}
      {selectedEntry && (() => {
        const SelectedIcon = selectedEntry.component;
        return (
          <div className="flex items-center gap-2 text-sm">
            <span className="text-muted-foreground text-xs">Selected:</span>
            <SelectedIcon className="h-4 w-4" />
            <span className="font-medium text-sm">{selectedEntry.label}</span>
            <span className="text-xs text-muted-foreground">({selectedEntry.category})</span>
          </div>
        );
      })()}
    </div>
  );
}
