import { useGetIconGroups } from "@/pages/editor/hooks/useIconData";
import { STICKER_DRAG_MIME } from "@/pages/editor/types/IconTypes";
import { useMemo } from "react";

const StickerInstruction = () => {
  const { data, isLoading, isError } = useGetIconGroups();

  const stickers = useMemo(() => {
    const groups = data?.data ?? [];
    return groups.flatMap((group) => group.icons);
  }, [data]);

  const handleDragStart = (
    e: React.DragEvent<HTMLImageElement>,
    url: string,
  ) => {
    e.dataTransfer.setData(STICKER_DRAG_MIME, url);
    e.dataTransfer.effectAllowed = "copy";
  };

  return (
    <div className="space-y-3">
      <div className="text-base font-bold">استیکر</div>
      <p className="text-sm text-gray-600">
        استیکر را بکشید و روی صفحه رها کنید
      </p>

      {isLoading && (
        <p className="text-sm text-gray-500">در حال بارگذاری استیکرها...</p>
      )}

      {isError && (
        <p className="text-sm text-red-500">خطا در بارگذاری استیکرها</p>
      )}

      {!isLoading && !isError && stickers.length === 0 && (
        <p className="text-sm text-gray-500">استیکری یافت نشد</p>
      )}

      {stickers.length > 0 && (
        <div className="grid grid-cols-3 gap-2  overflow-y-auto">
          {stickers.map((icon) => (
            <div
              key={icon.id}
              className="flex aspect-square items-center justify-center rounded-lg border border-gray-200 bg-gray-50 p-1 hover:border-blue-300 hover:bg-blue-50 transition-colors"
            >
              <img
                src={icon.url}
                alt=""
                draggable
                onDragStart={(e) => handleDragStart(e, icon.url)}
                className="max-h-full max-w-full object-contain cursor-grab active:cursor-grabbing"
              />
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

export default StickerInstruction;
