import { format } from "date-fns";
import { useState } from "react";
import { toast } from "sonner";
import { Button } from "../../../components/ui/button";
import {
	Card,
	CardContent,
	CardDescription,
	CardTitle,
} from "../../../components/ui/card";
import { Separator } from "../../../components/ui/separator";
import { api } from "../../../lib/apiHelper";

export default function Templates() {
	const [template, setTemplate] = useState(false);

	const getTemplate = async (type: "orders" | "forecast") => {
		setTemplate(true);
		try {
			const res = await api.get(`/logistics/dm/template?filename=${type}`, {
				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 = `Bulk${type.charAt(0).toUpperCase() + type.slice(1)}_Template-${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(`Template created for ${type}`);
			setTemplate(false);
		} catch {
			setTemplate(false);
			toast.error("There was an error getting the template");
		}
	};

	return (
		<div>
			<Card>
				<CardTitle>
					<p className="text-center">Templates</p>
				</CardTitle>
				<CardDescription className="w-64 p-2 ">
					<p>
						Clicking one of the template's below will generate an excel file you
						can fill out and re-upload, using the standard orders or standard
						forecast button
					</p>
					<Separator />
				</CardDescription>
				<CardContent>
					<div className="flex flex-rol justify-center gap-2">
						<Button onClick={() => getTemplate("orders")} disabled={template}>
							Orders
						</Button>
						<Button onClick={() => getTemplate("forecast")} disabled={template}>
							Forecast
						</Button>
					</div>
				</CardContent>
			</Card>
		</div>
	);
}
