import { useState } from "react";
import { getSession } from "next-auth/react";
import URLS from "@/redux/api/constants";

interface UseFileDownloadReturn {
  downloadFile: (endpoint: string, filename: string) => Promise<void>;
  isLoading: boolean;
  error: Error | null;
}

export function useFileDownload(): UseFileDownloadReturn {
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<Error | null>(null);

  const downloadFile = async (
    endpoint: string,
    filename: string
  ): Promise<void> => {
    setIsLoading(true);
    setError(null);

    try {
      const session = await getSession();
      const baseUrl = `${URLS.HOST_URL}${URLS.COMMON_SUFFIX_URL}`;
      const url = `${baseUrl}${endpoint}`;

      const headers: HeadersInit = new Headers();
      if (session?.accessToken) {
        headers.set("Authorization", `Bearer ${session.accessToken}`);
      }

      const response = await fetch(url, {
        method: "GET",
        headers,
        credentials: "same-origin",
        cache: "no-cache",
      });

      if (!response.ok) {
        throw new Error(
          `Failed to download file: ${response.status} ${response.statusText}`
        );
      }

      const blob = await response.blob();
      const objectUrl = window.URL.createObjectURL(blob);

      const link = document.createElement("a");
      link.href = objectUrl;
      link.setAttribute("download", filename);
      document.body.appendChild(link);
      link.click();
      link.remove();

      window.URL.revokeObjectURL(objectUrl);
    } catch (err) {
      const errorMessage =
        err instanceof Error ? err.message : "Unknown error occurred";
      setError(new Error(errorMessage));
      console.error("File download error:", err);
    } finally {
      setIsLoading(false);
    }
  };

  return { downloadFile, isLoading, error };
}
