import { useSuspenseQuery } from "@tanstack/react-query";
import * as Device from "expo-device";
import { useLocalSearchParams, useRouter } from "expo-router";
import { useState } from "react";
import {
	Button,
	Pressable,
	ScrollView,
	Text,
	useWindowDimensions,
	View,
} from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";
import Toast from "react-native-toast-message";
import { Card, CardContent } from "../../components/ui/card";
import { api } from "../../lib/apiHelper";
import { getActiveLoadingOrders } from "../../lib/queryStuff/getActiveLoadingOrders";

export default function DockPage() {
	const { id, currentLoading } = useLocalSearchParams<{
		id: string;
		currentLoading: string;
	}>();
	const router = useRouter();
	const [active] = useState(currentLoading !== "");

	const { width } = useWindowDimensions();
	const isTablet =
		Device.modelName?.toLowerCase().includes("et40") ||
		Device.modelName?.toLowerCase().includes("et45");

	const columns = isTablet ? 3 : 1;

	const gap = 8;
	const cardWidth =
		columns === 1 ? width - 16 : (width - gap * (columns + 1)) / columns;

	const {
		data: loadingOrders,
		refetch,
		isLoading,
	} = useSuspenseQuery(getActiveLoadingOrders());

	const dockFilter = loadingOrders.filter((i: any) => i.dockId === Number(id));

	// add in start loading order, if this is already on the dock we will disabled and change to view current pallets
	const startLoad = async (loadingOrder: string, dockId: string) => {
		try {
			const res = await api.post("/dockDoor/startLoad", {
				loadingOrder,
				dockId,
			});

			if (res.status === 200) {
				Toast.show({ type: "success", text1: res.data.message });
				refetch();
				return;
			}
		} catch (error) {
			Toast.show({
				type: "error",
				text1: JSON.stringify(error),
			});
		}
	};

	const endLoad = async (loadingOrder: string, dockId: string) => {
		try {
			const res = await api.post("/dockDoor/endLoad", {
				loadingOrder,
				dockId,
			});

			if (res.status === 200) {
				Toast.show({ type: "success", text1: res.data.message });
				refetch();
				return;
			}
		} catch (error) {
			Toast.show({
				type: "error",
				text1: JSON.stringify(error),
			});
		}
	};

	// add in ending loading order disabeled until all pallets are loaded.
	if (isLoading)
		return (
			<SafeAreaView>
				<Text>Loading</Text>
			</SafeAreaView>
		);
	return (
		<SafeAreaView>
			<View className="flex flex-row justify-between gap-1 ml-1 mr-1">
				<View>
					<Pressable
						onPress={() => router.back()}
						className="self-start rounded-xl bg-gray-200 px-4 py-2"
					>
						<Text className="font-semibold">← Back</Text>
					</Pressable>
				</View>

				<Text className="text-xl mt-1">{dockFilter[0].dockDescription}</Text>
				<View>
					<Pressable
						onPress={() =>
							router.push({
								pathname: "/dock/scans/[scanner]",
								params: {
									scanner: id,
								},
							})
						}
						className="self-start rounded-xl bg-gray-200 px-4 py-2"
					>
						<Text className="font-semibold">Scans</Text>
					</Pressable>
				</View>
			</View>
			<ScrollView>
				<View className="w-full flex-row flex-wrap gap-2 m-2">
					{dockFilter.map((i: any) => {
						return (
							<View key={i.id}>
								<Card
									style={{
										borderWidth: 4,
										width: cardWidth,
									}}
								>
									<CardContent>
										<View>
											<Text>Loading Order: {dockFilter[0].id}</Text>
											<Text>
												{`${dockFilter[0].loadingPlanItems[0].articleId} - ${dockFilter[0].loadingPlanItems[0].articleDescription}`}
											</Text>
											<Text>
												Current Loaded :{" "}
												{dockFilter[0].loadingPlanItems[0].loadedQuantityLUs} /{" "}
												{dockFilter[0].loadingPlanItems[0].plannedQuantityLUs}
											</Text>
										</View>
										<View className="mt-2 flex flex-row gap-2 justify-between">
											<Button
												title="Start Load"
												onPress={() =>
													startLoad(dockFilter[0].id.toString(), id)
												}
												disabled={active}
											/>
											<Button
												title="End Load"
												onPress={() => endLoad(dockFilter[0].id.toString(), id)}
												disabled={active}
											/>
										</View>
									</CardContent>
								</Card>
							</View>
						);
					})}
				</View>
			</ScrollView>
		</SafeAreaView>
	);
}
