import { ServerRequest } from "@/lib/actions";
import { getExtension } from "@/lib/utils";
import { ProjectFilesTree } from "@/models/projectFilesTree";
import { SupportedFiles } from "@/models/supportedFiles";
import fetchFileContent from "@/services/files/fetchFileContent";
import { Dispatch, SetStateAction } from "react";
import { toast } from "sonner";

type ViewItemProps = {
  item: ProjectFilesTree;
  setPath: Dispatch<SetStateAction<string>>;
  setIsFileView: any;
  setFile: any;
  dict: Dictionary;
};
export default async function ViewItem({
  item,
  setPath,
  setIsFileView,
  setFile,
  dict,
}: ViewItemProps) {
  if (!item.type) {
    return setPath(item.path);
  }

  const promise = new Promise(async (resolve, reject) => {
    const formData = new FormData();
    formData.append("dir", item.path);
    formData.append("file", item.name);

    const type = getExtension(item.name);

    let isSupported: false | "code" | "image" | "video" | "doc" = false;

    for (const keys in SupportedFiles) {
      if (SupportedFiles[keys as keyof typeof SupportedFiles].includes(type)) {
        isSupported = keys as "code" | "image" | "video" | "doc";
      }
    }

    if (!isSupported) {
      return reject({ message: dict.alerts.view_file.not_supported });
    }

    const result = await ServerRequest<any>(fetchFileContent(formData));

    setPath(item.path);
    setIsFileView(isSupported);
    setFile(result ? { content: result.data.content, type } : undefined);
    resolve(result);
  });

  toast.promise(promise, {
    loading: dict.alerts.view_file.loading,
    error: ({ message }: any) => message,
  });
}
