// src/utils/storage.js
import React from "react";
import {
  IoFileTray,
  IoFolderOpen,
  IoDocumentTextOutline,
  IoImageOutline,
  IoVideocamOutline,
  IoMusicalNotesOutline,
  IoGlobeOutline,
  IoColorPaletteOutline,
  IoArchiveOutline,
  IoLinkOutline,
  IoStatsChartOutline,
} from "react-icons/io5";

import {
  FaFilePdf,
  FaFileWord,
  FaFileExcel,
  FaFilePowerpoint,
  FaFileImage,
  FaFileArchive,
  FaFileAudio,
  FaFileVideo,
  FaGlobe,
  FaLink,
} from "react-icons/fa";

/* -------------------- constants -------------------- */
export const SEARCH_TYPES = [
  "پوشه‌ها",
  "اسناد",
  "صفحات گسترده",
  "ارائه‌ها",
  "ویدیوها",
  "فرم‌ها",
  "تصاویر",
  "فایل‌های فشرده",
  "PDF ها",
  "نقاشی‌ها",
  "میانبرها",
  "وب‌سایت‌ها",
  "فایل‌های صوتی",
];

export const CATEGORY_ICON_MAP = {
  پوشه‌ها: IoFolderOpen,
  اسناد: IoDocumentTextOutline,
  "صفحات گسترده": IoStatsChartOutline,
  ارائه‌ها: IoDocumentTextOutline,
  ویدیوها: IoVideocamOutline,
  فرم‌ها: IoDocumentTextOutline,
  تصاویر: IoImageOutline,
  "فایل‌های فشرده": IoArchiveOutline,
  "PDF ها": IoDocumentTextOutline,
  نقاشی‌ها: IoColorPaletteOutline,
  میانبرها: IoLinkOutline,
  وب‌سایت‌ها: IoGlobeOutline,
  "فایل‌های صوتی": IoMusicalNotesOutline,
};

export const TYPE_EXTENSION_MAP = {
  اسناد: ["doc", "docx", "pdf", "txt", "rtf", "odt", "md"],
  "صفحات گسترده": ["xls", "xlsx", "csv", "ods"],
  ارائه‌ها: ["ppt", "pptx", "key", "odp"],
  ویدیوها: ["mp4", "mkv", "avi", "mov", "wmv"],
  فرم‌ها: ["html", "php"],
  تصاویر: ["jpg", "jpeg", "png", "gif", "svg", "webp"],
  "فایل‌های فشرده": ["zip", "rar", "7z", "tar", "gz"],
  "PDF ها": ["pdf"],
  نقاشی‌ها: ["psd", "ai", "xd", "fig", "sketch"],
  میانبرها: ["lnk", "url", "shortcut"],
  وب‌سایت‌ها: ["html", "htm"],
  "فایل‌های صوتی": ["mp3", "wav", "ogg", "m4a", "flac"],
};

/* -------------------- id helpers -------------------- */
export const getFileId = (f) => f?.id ?? f?.file_id ?? f?.uuid ?? f?.pk;
export const getFolderId = (f) => f?.id ?? f?.folder_id ?? f?.uuid ?? f?.pk;

/* -------------------- url helpers -------------------- */
export const joinUrl = (base, path) => {
  const b = String(base || "");
  const p = String(path || "");

  if (!b) return p;
  if (!p) return b;

  // ✅ اگر path خودش URL کامل بود، خرابش نکن
  if (/^https?:\/\//i.test(p)) return p;

  const b2 = b.endsWith("/") ? b.slice(0, -1) : b;
  const p2 = p.startsWith("/") ? p : `/${p}`;
  return `${b2}${p2}`;
};

/* -------------------- file helpers -------------------- */
export const getFileExtension = (name = "") => {
  const idx = name.lastIndexOf(".");
  if (idx === -1) return "";
  return name.slice(idx + 1).toLowerCase();
};

// ✅ جایگزین این 2 تا تو src/utils/storage.js
export const isZipFile = (file) => {
  const ext = getFileExtension(file?.name || "");
  if (ext === "zip") return true;

  const mt = String(
    file?.current_version?.mime_type ||
      file?.mime_type ||
      file?.preview?.thumb_mime ||
      ""
  ).toLowerCase();

  return mt.includes("zip");
};

export const isImageFile = (file) => {
  const mt = String(
    file?.current_version?.mime_type ||
      file?.mime_type ||
      file?.preview?.thumb_mime ||
      ""
  ).toLowerCase();

  return mt.startsWith("image/");
};

export const formatDate = (dateStr) => {
  if (!dateStr) return "-";
  try {
    return new Date(dateStr).toLocaleDateString("fa-IR");
  } catch {
    return dateStr;
  }
};

export const formatSize = (bytes) => {
  if (bytes == null || Number.isNaN(Number(bytes))) return "-";
  const b = Number(bytes);
  if (b < 1024) return `${b} B`;
  const kb = b / 1024;
  if (kb < 1024) return `${kb.toFixed(1)} KB`;
  const mb = kb / 1024;
  if (mb < 1024) return `${mb.toFixed(1)} MB`;
  const gb = mb / 1024;
  return `${gb.toFixed(1)} GB`;
};

export const flattenFilesFromFolders = (folders = [], parentPath = "") => {
  let result = [];
  folders.forEach((folder) => {
    const folderName = folder.name || "بدون نام";
    const currentPath = parentPath ? `${parentPath}/${folderName}` : folderName;

    (folder.files || []).forEach((file) =>
      result.push({ ...file, folderPath: currentPath })
    );
    if (folder.folders && folder.folders.length > 0) {
      result = result.concat(flattenFilesFromFolders(folder.folders, currentPath));
    }
  });
  return result;
};

export const flattenFolderTree = (rootFolders) => {
  const res = [];
  const walk = (list, depth = 0) => {
    (list || []).forEach((f) => {
      res.push({ id: getFolderId(f), name: f?.name || "بدون نام", depth });
      if (f?.folders?.length) walk(f.folders, depth + 1);
    });
  };
  walk(rootFolders || [], 0);
  return res;
};

/* -------------------- color helpers -------------------- */
export const normalizeHex = (hex) => {
  const h = String(hex || "").trim();
  if (!h) return "";
  return h.startsWith("#") ? h.toUpperCase() : `#${h.toUpperCase()}`;
};

export const hexToRgba = (hex, a = 0.18) => {
  const h = normalizeHex(hex).replace("#", "");
  if (h.length !== 6) return `rgba(0,0,0,${a})`;
  const r = parseInt(h.slice(0, 2), 16);
  const g = parseInt(h.slice(2, 4), 16);
  const b = parseInt(h.slice(4, 6), 16);
  return `rgba(${r}, ${g}, ${b}, ${a})`;
};

export const getEffectiveHex = (item) =>
  normalizeHex(item?.effective_color_hex || item?.color_hex || "#000000");

export const getItemColorStyle = (item, opacity = 1) => {
  const hex = item?.effective_color_hex || "#000000";
  return { color: hex, opacity };
};

/* -------------------- icons -------------------- */
export const FileTypeIcon = ({ ext, className = "h-5 w-5", style }) => {
  const e = (ext || "").toLowerCase();

  if (["jpg", "jpeg", "png", "gif", "svg", "webp"].includes(e))
    return <FaFileImage className={className} style={style} />;

  if (["pdf"].includes(e)) return <FaFilePdf className={className} style={style} />;
  if (["doc", "docx", "odt", "rtf"].includes(e))
    return <FaFileWord className={className} style={style} />;
  if (["xls", "xlsx", "csv", "ods"].includes(e))
    return <FaFileExcel className={className} style={style} />;
  if (["ppt", "pptx", "key", "odp"].includes(e))
    return <FaFilePowerpoint className={className} style={style} />;
  if (["zip", "rar", "7z", "tar", "gz"].includes(e))
    return <FaFileArchive className={className} style={style} />;
  if (["mp3", "wav", "ogg", "m4a", "flac"].includes(e))
    return <FaFileAudio className={className} style={style} />;
  if (["mp4", "mkv", "avi", "mov", "wmv"].includes(e))
    return <FaFileVideo className={className} style={style} />;
  if (["html", "htm"].includes(e)) return <FaGlobe className={className} style={style} />;
  if (["lnk", "url", "shortcut"].includes(e))
    return <FaLink className={className} style={style} />;

  return <IoFileTray className={className} style={style} />;
};

/* -------------------- preview helpers -------------------- */
// ✅ baseURL api مثل: http://localhost:8000/api/  => public: http://localhost:8000
export const getPublicBaseUrl = (apiBaseURL) => {
  const b = String(apiBaseURL || "").trim();
  if (!b) return "";
  try {
    const u = new URL(b);
    return `${u.protocol}//${u.host}`;
  } catch {
    // fallback: حذف /api از آخر (و اسلش‌های اضافی)
    return b.replace(/\/api\/?$/, "").replace(/\/+$/, "");
  }
};

// ✅ همین مهمه: اگر بک‌اند presigned URL کامل داد، همونو برگردون
export const getPreviewUrl = (apiBaseURL, file) => {
  const p = file?.preview;
  if (!p || p.status !== "ready") return null;

  const tu = String(p.thumb_url || "").trim();
  if (!tu) return null;

  // ✅ URL کامل (presigned) — دست نزن
  if (tu.startsWith("http://") || tu.startsWith("https://")) return tu;

  // ✅ نسبی — به publicBase بچسبون
  const publicBase = getPublicBaseUrl(apiBaseURL);
  return joinUrl(publicBase, tu);
};
