import { useState, useEffect, useRef, useCallback } from "react";
import { useIconPicker } from "./IconPickerContext";
import { cn, isLight } from "@/lib/utils";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { IconType } from "./types";
import { faSearch } from "@fortawesome/free-solid-svg-icons";
import { ScrollArea } from "@/components/ui/scroll-area";
import { useScrollAreaEnd } from "./hooks";
import FontAndColor from "./font-and-color";
import { Badge } from "../ui/badge";

interface VirtualIconGridProps {
  allIcons: IconType[];
}

export function VirtualIconGrid({ allIcons }: VirtualIconGridProps) {
  const { size, color, selectedIcon, setSelectedIcon, searchQuery } =
    useIconPicker();
  const [hoveredIcon, setHoveredIcon] = useState<string | null>(null);
  const [visibleIcons, setVisibleIcons] = useState<IconType[]>([]);
  const [hasMore, setHasMore] = useState(true);
  const scrollRef = useRef<HTMLDivElement>(null);
  const initialLoadCount = 200;
  const loadIncrement = 30;
  const bgColor = isLight(color)
    ? "#1f2937" // dark slate
    : "#f1f5f9"; // light slate

  const filteredIcons = useRef<IconType[]>([]); // store filtered list

  useEffect(() => {
    const filtered = allIcons.filter((icon) =>
      icon.name.toLowerCase().includes(searchQuery.toLowerCase()),
    );
    filteredIcons.current = filtered;
    setVisibleIcons(filtered.slice(0, initialLoadCount));
    setHasMore(filtered.length > initialLoadCount);
  }, [searchQuery, allIcons]);

  const loadMoreIcons = useCallback(() => {
    if (!hasMore) return;

    const current = filteredIcons.current;
    const nextBatch = current.slice(
      visibleIcons.length,
      visibleIcons.length + loadIncrement,
    );

    if (nextBatch.length > 0) {
      setVisibleIcons((prev) => [...prev, ...nextBatch]);
      setHasMore(visibleIcons.length + nextBatch.length < current.length);
    } else {
      setHasMore(false);
    }
  }, [visibleIcons.length, hasMore]);

  const handleIconClick = (iconName: string) => {
    setSelectedIcon(iconName);
    const icon = allIcons.find((i) => i.name === iconName);
    if (icon) navigator.clipboard.writeText(iconName).catch(() => {});
  };

  const selectedIconData = selectedIcon
    ? allIcons.find((i) => i.name === selectedIcon)
    : null;

  useScrollAreaEnd(scrollRef, loadMoreIcons, 0.99);

  return (
    <div className='relative flex flex-col gap-4'>
      <FontAndColor />

      {selectedIcon && selectedIconData && (
        <div className=' px-6'>
          <div className=' flex w-full justify-center items-center border  rounded-md h-20 relative'>
            <Badge
              variant={"outline"}
              className=' absolute -top-3 left-3 bg-white'
            >
              Selected
            </Badge>
            <div
              style={{ backgroundColor: bgColor }}
              className='rounded-full overflow-hidden p-3 shadow-md border border-primary/30 flex items-center justify-center'
            >
              <FontAwesomeIcon
                icon={selectedIconData.icon}
                style={{ color, fontSize: size }}
                className={`text-xl`}
              />
            </div>
          </div>
        </div>
      )}

      <ScrollArea className='h-[21rem] overflow-auto ' ref={scrollRef}>
        {visibleIcons.length === 0 ? (
          <div className='flex flex-col  items-center justify-center h-40 text-muted-foreground'>
            <FontAwesomeIcon
              icon={faSearch}
              className='w-8 h-8 mb-2 opacity-40'
            />
            <p>No icons found</p>
            <p className='text-sm'>Try adjusting your search.</p>
          </div>
        ) : (
          <div className='py-1 grid grid-cols-[repeat(auto-fit,_minmax(35px,_1fr))] gap-2 px-6'>
            {visibleIcons.map((icon) => {
              const isSelected = selectedIcon === icon.name;
              const isHovered = hoveredIcon === icon.name;

              return (
                <div
                  key={icon.id}
                  className={cn(
                    "flex flex-col border  items-center justify-center gap-2 p-1 rounded-lg cursor-pointer transition-all group",
                    "hover:bg-muted hover:scale-105 hover:shadow-sm",
                    isSelected && "bg-primary/10 ring-1 ring-primary/30",
                  )}
                  onMouseEnter={() => setHoveredIcon(icon.name)}
                  onMouseLeave={() => setHoveredIcon(null)}
                  onClick={() => handleIconClick(icon.name)}
                >
                  <div
                    className={cn(
                      "flex items-center  justify-center w-8 h-8 rounded-md transition-all",
                      isSelected ? "text-primary" : "text-foreground",
                      isHovered && !isSelected && "text-primary/80",
                    )}
                  >
                    <FontAwesomeIcon
                      icon={icon.icon}
                      className={`text-md text-[#0b0417]`}
                    />
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </ScrollArea>
    </div>
  );
}
