import React from "react";
import { IoEllipsisVertical, IoFolderOpen } from "react-icons/io5";
import { getFolderId } from "../../utils/storage";
import ActionMenuPortal from "./ActionMenuPortal";
import { TbDotsVertical } from "react-icons/tb";

export default function FoldersGrid({
  folders = [],
  onOpenFolder, // (folder) => void
  folderMenu,
  onToggleFolderMenu,
  onCloseFolderMenu,
  renderFolderMenu, // (folder) => ReactNode
}) {
  if (!folders.length) return null;

  return (
    <ul className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3 sm:gap-4 py-3 sm:py-4">
      {folders.map((folder) => {
        const fid = getFolderId(folder);
        const filesCount = folder?.files_count ?? (Array.isArray(folder?.files) ? folder.files.length : 0);
        const foldersCount = folder?.folders_count ?? (Array.isArray(folder?.folders) ? folder.folders.length : 0);

        return (
          <li
            key={String(fid)}
            onClick={() => onOpenFolder?.(folder)}
            className="relative min-w-0 rounded-2xl p-4 bg-[#A1E3F980] shadow dark:bg-[#A1E3F919]
              hover:bg-[#f2f2f2] dark:hover:bg-[#001F3F]
              border border-black/5 dark:border-white/10
              transition-colors cursor-pointer"
          >
            <div className="flex items-start justify-between gap-3 min-w-0">
              <div className="flex gap-3 items-center min-w-0">
                <div className="w-11 h-11 rounded-2xl bg-white/70 dark:bg-white/10 border border-black/10 dark:border-white/10 flex items-center justify-center shrink-0">
                  <IoFolderOpen className="h-6 w-6 text-[#43BEFF]" />
                </div>

                <div className="min-w-0">
                  <p className="truncate font-bold flex items-center gap-1 text-sm sm:text-base">
                    {folder?.name || "بدون نام"}
                  </p>

                  <p className="text-xs mt-2 dark:text-white/60 text-black/50 truncate">
                    {foldersCount} فولدر • {filesCount} فایل
                  </p>
                </div>
              </div>

              <button
                type="button"
                className="p-2 rounded-xl hover:bg-black/5 dark:hover:bg-white/10 shrink-0"
                onPointerDown={(e) => {
                  e.preventDefault();
                  e.stopPropagation();
                }}
                onClick={(e) => onToggleFolderMenu?.(fid, e)}
              >
                <IoEllipsisVertical className="h-5 w-5 dark:text-white text-black"/>
              </button>

              <ActionMenuPortal
                open={String(folderMenu?.id) === String(fid)}
                rect={folderMenu?.rect}
                onClose={onCloseFolderMenu}
                width={280}
              >
                {renderFolderMenu?.(folder)}
              </ActionMenuPortal>
            </div>
          </li>
        );
      })}
    </ul>
  );
}
