import { useRef, 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";
import { useSession } from "../../../lib/auth-client";

export default function ForecastUpload({
	server,
	responseData,
}: {
	server: string;
	responseData: any;
}) {
	const fileInputRef = useRef<HTMLInputElement | null>(null);
	const [posting, setPosting] = useState(false);
	const [selectedFileType, setSelectedFileType] = useState<string>("");
	const { data: session } = useSession();

	const importOrders = async (e: React.ChangeEvent<HTMLInputElement>) => {
		console.log("clicked import");
		responseData([]);
		const file = e.target.files?.[0];
		if (!file) {
			toast.error("Missing or no file was selected please try again");
			setPosting(false);
			return;
		}

		// create the form data with the correct fileType
		const formData = new FormData();
		formData.append("file", file);
		formData.append("fileType", selectedFileType); // extra field
		formData.append("username", `${session?.user.username}`);

		toast.success("Import started.");
		try {
			const response = await api.post("/logistics/dm/forecast", formData, {
				headers: {
					"Content-Type": "multipart/form-data",
				},
				validateStatus: (status) => status < 500,
			});
			//console.log("Upload successful:", response.data);

			if (fileInputRef.current) {
				fileInputRef.current.value = "";
			}
			setPosting(false);

			if (response.status === 200) {
				toast.success(response?.data?.message);

				responseData(response.data.data);
			} else {
				toast.error(response?.data?.message);
			}
		} catch (error) {
			console.error(error);
			toast.error("Upload failed");
		}
		setPosting(false);
	};

	const handleButtonClick = (type: string) => {
		setPosting(true);

		const handleFocus = () => {
			setTimeout(() => {
				if (!fileInputRef.current?.files?.length) {
					setPosting(false);
				}
			}, 0);
		};

		window.addEventListener("focus", handleFocus, { once: true });
		setSelectedFileType(type);
		fileInputRef.current?.click();
	};

	const ForecastButton = ({ name, type }: { name: string; type: string }) => {
		return (
			<div>
				<Button onClick={() => handleButtonClick(type)} disabled={posting}>
					{name}
				</Button>
			</div>
		);
	};

	// For plants that basically use the same import set like this so we dont have weird looking cards
	const pngForecast = ["usiow1", "usiow2", "usksc1"];
	return (
		<div>
			<div>
				<Card>
					<CardTitle>
						<p className="text-center">Forecast</p>
					</CardTitle>
					<CardDescription className="w-64 p-2 ">
						<p className="text-xs">
							When clicking on one of the below options you will need to upload
							the respective file to be processed to 2.0
						</p>
						<Separator />
					</CardDescription>
					<CardContent>
						<div className="grid grid-cols-2 gap-2">
							<ForecastButton name={"Standard"} type={"standard"} />
							{server === "usday1" ||
								(server.includes("test") && (
									<ForecastButton
										name={"Energizer Forecast"}
										type={"energizer"}
									/>
								))}

							{pngForecast.includes(server) ||
								(server.includes("test") && (
									<ForecastButton name={"PnG"} type={"pg"} />
								))}

							{server === "usflo1" ||
								(server.includes("test") && (
									<ForecastButton name={"VMI Import"} type={"loreal"} />
								))}
						</div>
					</CardContent>
				</Card>
			</div>
			<input
				type="file"
				accept=".xlsx, .xls, .xlsm"
				ref={fileInputRef}
				style={{ display: "none" }}
				onChange={importOrders}
			/>
		</div>
	);
}
