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 ForecastImport(props: any) {
    const fileInputRef: any = useRef(null);
    const [posting, setPosting] = useState(false);
    //const token = localStorage.getItem("auth_token");
    const { session } = useAuth();
    //const [fileType, setFileType] = useState("");
    const navigate = useNavigate();
    const router = useRouterState();
    const currentPath = router.location.href;

    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("postForecast", e.target.files[0]);
        formData.append("fileType", props.fileType); // extra field
        formData.append("username", `${session?.user.username}`);

        // console.log(formData);
        toast.success("Import started.");
        try {
            const response = await axios.post(
                "/lst/old/api/logistics/postforecastin",
                formData,
                {
                    headers: {
                        "Content-Type": "multipart/form-data",
                    },
                }
            );
            //console.log("Upload successful:", response.data);
            toast.success(response?.data?.message);
            fileInputRef.current.value = null;
            setPosting(false);
            // toast.success(
            //     "File Uploaded, please validate processing in alplaprod 2.0"
            // );
            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>
    );
}
