import axios from "axios";
import { format } from "date-fns";
import { useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";

export default function StandardForecastTemplate() {
	const [template, setTemplate] = useState(false);
	const getTemplate = async () => {
		setTemplate(true);
		try {
			const res = await axios.get(
				`/lst/old/api/logistics/bulkforcasttemplate`,
				{
					responseType: "blob",
				},
			);

			const blob = new Blob([res.data], {
				type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
			});

			const link = document.createElement("a");
			link.href = window.URL.createObjectURL(blob);
			link.download = `ForecastTemplate-${format(new Date(Date.now()), "M-d-yyyy")}.xlsx`; // You can make this dynamic
			document.body.appendChild(link);
			link.click();

			// Clean up
			document.body.removeChild(link);
			window.URL.revokeObjectURL(link.href);
			toast.success(`Forecast template`);
			setTemplate(false);
		} catch (error) {
			setTemplate(false);
			toast.error("There was an error getting the template");
		}
	};
	return (
		<Button onClick={getTemplate} disabled={template}>
			Standard Forecast Template
		</Button>
	);
}
