import { useCallback, useEffect, useMemo, useRef, useState } from "react";

const getFileId = (f) => f?.id ?? f?.file_id ?? f?.uuid ?? f?.pk;
const getFolderId = (f) => f?.id ?? f?.folder_id ?? f?.uuid ?? f?.pk;

export function useStorageItemsTree({ Axiosinstance, toast }) {
  const [tree, setTree] = useState([]); // با root
  const [loading, setLoading] = useState(false);
  const [loadError, setLoadError] = useState(null);

  const inFlightRef = useRef(false);
  const mountedRef = useRef(false);

  const fetchStarred = useCallback(async () => {
    try {
      const [filesRes, foldersRes] = await Promise.all([
        Axiosinstance.get("storage/starred/"),
        Axiosinstance.get("storage/folders/starred/"),
      ]);

      const filesData = filesRes.data;
      const foldersData = foldersRes.data;

      let starredFiles = [];
      let starredFolders = [];

      if (Array.isArray(filesData)) starredFiles = filesData;
      else if (Array.isArray(filesData?.files)) starredFiles = filesData.files;
      else if (Array.isArray(filesData?.results)) starredFiles = filesData.results;

      if (Array.isArray(foldersData)) starredFolders = foldersData;
      else if (Array.isArray(foldersData?.folders)) starredFolders = foldersData.folders;
      else if (Array.isArray(foldersData?.results)) starredFolders = foldersData.results;

      return {
        fileIds: new Set(starredFiles.map((f) => String(getFileId(f)))),
        folderIds: new Set(starredFolders.map((f) => String(getFolderId(f)))),
      };
    } catch {
      return { fileIds: new Set(), folderIds: new Set() };
    }
  }, [Axiosinstance]);

  const applyStarsRecursive = useCallback((folders, starred) => {
    return (folders || []).map((folder) => ({
      ...folder,
      is_starred: starred.folderIds.has(String(getFolderId(folder))) || !!folder.is_starred,
      files: (folder.files || []).map((file) => ({
        ...file,
        is_starred: starred.fileIds.has(String(getFileId(file))) || !!file.is_starred,
      })),
      folders: folder.folders ? applyStarsRecursive(folder.folders, starred) : [],
    }));
  }, []);

  const requestRefresh = useCallback(
    async ({ silent = false } = {}) => {
      if (inFlightRef.current) return;
      inFlightRef.current = true;

      try {
        if (!silent) setLoading(true);
        setLoadError(null);

        const [itemsRes, starred] = await Promise.all([
          Axiosinstance.get("storage/items/"),
          fetchStarred(),
        ]);

        const data = itemsRes.data || {};
        const foldersRaw = data.folders || [];
        const rootFiles = data.files || [];

        const treeWithRoot = [
          {
            id: "root",
            name: "فایل‌های من",
            is_starred: false,
            in_trash: false,
            owner_email: null,
            files: (rootFiles || []).map((f) => ({
              ...f,
              is_starred: starred.fileIds.has(String(getFileId(f))) || !!f.is_starred,
            })),
            folders: applyStarsRecursive(foldersRaw, starred),
          },
        ];

        setTree(treeWithRoot);
      } catch (err) {
        const msg = "خطا در دریافت داده‌ها. لطفاً بعداً دوباره امتحان کنید.";
        setLoadError(msg);
        toast?.error?.(msg);
      } finally {
        if (!silent) setLoading(false);
        inFlightRef.current = false;
      }
    },
    [Axiosinstance, applyStarsRecursive, fetchStarred, toast]
  );

  useEffect(() => {
    if (mountedRef.current) return;
    mountedRef.current = true;
    requestRefresh({ silent: false });
  }, [requestRefresh]);

  return { tree, loading, loadError, requestRefresh };
}
