import { Button } from "@/components/ui/button";
import axios from "axios";
import { useRef, useState } from "react";
import { toast } from "sonner";

export default function ForecastImport(props: any) {
    const fileInputRef: any = useRef(null);
    const [posting, setPosting] = useState(false);
    const token = localStorage.getItem("auth_token");
    //const [fileType, setFileType] = useState("");
    const importOrders = async (e: any) => {
        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
        // console.log(formData);
        toast.success("Import started.");
        try {
            const response = await axios.post(
                "/api/logistics/postforecastin",
                formData,
                {
                    headers: {
                        "Content-Type": "multipart/form-data",
                        Authorization: `Bearer ${token}`,
                    },
                }
            );
            //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>
    );
}
