import axios from "axios";
import { useRef, useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { useAuth } from "@/lib/authClient";
import { useNavigate, useRouterState } from "@tanstack/react-router";

export default function OrderImport(props: any) {
    const fileInputRef: any = useRef(null);
    const [posting, setPosting] = useState(false);
    const { session } = useAuth();
    const navigate = useNavigate();
    const router = useRouterState();
    const currentPath = router.location.href;
    //const [fileType, setFileType] = useState("");
    const importOrders = async (e: any) => {
        if (!session || !session.user) {
            toast.error("You are allowed to do this unless you are logged in");
            navigate({ to: "/login", search: { redirect: currentPath } });
            return;
        }
        const file = e.target.files[0];
        if (!file) {
            toast.error("Missing file please try again");
            setPosting(false);
            return;
        }

        // create the form data with the correct fileType
        const formData = new FormData();
        formData.append("postOrders", e.target.files[0]);
        formData.append("fileType", props.fileType); // extra field
        formData.append("username", `${session?.user.username}`);

        try {
            const response = await axios.post(
                "/lst/old/api/logistics/postbulkorders",
                formData,
                {
                    headers: {
                        "Content-Type": "multipart/form-data",
                    },
                }
            );
            //console.log("Upload successful:", response.data);
            toast.success(response?.data?.message);
            fileInputRef.current.value = null;
            setPosting(false);
        } catch (error) {
            console.log(error);
            toast.error("Upload failed");
        }
        setPosting(false);
    };

    const handleButtonClick = () => {
        setPosting(true);
        fileInputRef.current.click();
    };
    return (
        <div>
            <Button onClick={handleButtonClick} disabled={posting}>
                {props.name}
            </Button>
            <input
                type="file"
                accept=".xlsx, .xls, .xlsm"
                ref={fileInputRef}
                style={{ display: "none" }}
                onChange={importOrders}
            />
        </div>
    );
}
