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

export default function StandardOrderTemplate() {
    const [template, setTemplate] = useState(false);
    const getTemplate = async () => {
        setTemplate(true);
        try {
            const res = await axios.get(`/api/logistics/bulkorderstemplate`, {
                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 = `BulkOrderTemplate-${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(`Bulk Order template`);
            setTemplate(false);
        } catch (error) {
            setTemplate(false);
            toast.error("There was an error getting the tempalte");
        }
    };
    return (
        <Button onClick={getTemplate} disabled={template}>
            Standard Order Template
        </Button>
    );
}
