import { faDownload } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { useDownloadLogFiles } from "../../../hooks/useDownloadLogFiles";
import { toast } from "sonner";

const DownloadLogButton = () => {
  const { downloadLogFilesQuery } = useDownloadLogFiles();
  const isLoading = downloadLogFilesQuery?.isFetching;

  const handleDownloadClick = async () => {
    try {
      const blob = await downloadLogFilesQuery?.refetch().then((res) => res.data);
      if (!blob) {
        throw new Error("No log file data received");
      }
      const url = window.URL.createObjectURL(new Blob([blob]));
      const link = document.createElement("a");
      if (!link) {
        throw new Error("Failed to create download link");
      } else {
        link.href = url;
        link.setAttribute("download", "FlexiAI-0.log");
        document.body.appendChild(link);
        link.click();
        link.parentNode?.removeChild(link);
        window.URL.revokeObjectURL(url);
      }
    } catch (error: unknown) {
      const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
      toast.error(errorMessage);
    }
  };

  return (
    <button
      className="p-3 border border-gray-700 rounded-lg hover:bg-[#233241] hover:cursor-pointer"
      onClick={handleDownloadClick}
    >
      <div className="flex flex-row gap-2 items-center">
        <span className="font-bold text-xl bg-slate-700 p-1 px-2 rounded-md">
          <FontAwesomeIcon icon={faDownload} />
        </span>
        <p className="text-lg">{"Download Log Files"}</p>
      </div>
      <p className="text-slate-400 italic text-start">{isLoading ? "Downloading..." : "View logs"}</p>
    </button>
  );
};

export default DownloadLogButton;
