import { format } from "date-fns-tz";
import * as Device from "expo-device";
import { useFocusEffect } from "expo-router";
import type React from "react";
import { useCallback, useEffect, useMemo, useState } from "react";
import {
	Button,
	ScrollView,
	Text,
	useWindowDimensions,
	View,
} from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";
import { Card, CardContent } from "../../components/ui/card";
import { useSocketRoom } from "../../hooks/socket.io.hook";

type PPOO = {
	type: string;
	items: any;
	createdAt: Date;
};
export default function PPOO() {
	const { data } = useSocketRoom<any>("ppoo", undefined, "replace") as any;
	const [sortDir, setSortDir] = useState<"asc" | "desc">("desc");

	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 items = data?.items ?? [];
	const sortedItems = useMemo(() => {
		return [...items].sort((a, b) => {
			const aDate = new Date(a.lastMovingDate).getTime();
			const bDate = new Date(b.lastMovingDate).getTime();

			return sortDir === "asc" ? aDate - bDate : bDate - aDate;
		});
	}, [items, sortDir]);

	//console.log(logsInfo);

	return (
		<View className="flex items-center mt-2">
			<View className="flex m-2">
				<Button
					onPress={() =>
						setSortDir((prev) => (prev === "asc" ? "desc" : "asc"))
					}
					title={`Sort: ${sortDir}`}
				/>
			</View>
			{sortedItems.length === 0 ? (
				<View className="flex items-center">
					<Text>Loading PPOO...</Text>
				</View>
			) : (
				<SafeAreaView className="flex-1">
					<ScrollView className="w-full">
						<View className="w-full flex-row flex-wrap gap-2 m-2">
							{sortedItems.map((i: any) => {
								return (
									<View key={i.runningNumber}>
										<Card
											//className={isTablet ? "w-[32%]" : "w-full"}
											style={{
												borderColor:
													i.mainDefectId === 864
														? "blue"
														: i.state === "QualityBlocked"
															? "red"
															: undefined,
												borderWidth: 4,
												width: cardWidth,
											}}
										>
											<CardContent>
												<Text>
													{i.articleId} - {i.articleName}
												</Text>

												<Text>
													Running Number: {i.runningNumber ?? "Non barcoded"}
												</Text>
												<Text>
													Date: {format(i.lastMovingDate, "M/d/yyyy HH:mm")}
												</Text>
											</CardContent>
										</Card>
									</View>
								);
							})}
						</View>
					</ScrollView>
				</SafeAreaView>
			)}
		</View>
	);
}
