"use client";

import { Bar, BarChart, CartesianGrid, XAxis } from "recharts";

import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
	ChartConfig,
	ChartContainer,
	ChartTooltip,
	ChartTooltipContent,
} from "@/components/ui/chart";

const chartConfig = {
	value: {
		label: "Count",
		color: "hsl(var(--chart-1))",
	},
	foldtime: {
		label: "Fold Time",
		color: "hsl(var(--chart-2))",
	},
} satisfies ChartConfig;

export function MinuteChart({
	data,
}: {
	data: {
		timestamp: number;
		foldtime: number;
	}[];
}) {
	const thisHourTimestamp = new Date();
	thisHourTimestamp.setMinutes(0, 0, 0);
	const nextHourTimestamp = new Date();
	nextHourTimestamp.setHours(nextHourTimestamp.getHours() + 1);
	nextHourTimestamp.setMinutes(0, 0, 0);

	console.log(thisHourTimestamp.getTime(), nextHourTimestamp.getTime());

	const todayData = data.filter(
		(data) =>
			data.timestamp >= thisHourTimestamp.getTime() &&
			data.timestamp < nextHourTimestamp.getTime()
	);

	const todayDataPerHour = todayData.reduce((acc, data) => {
		const hour = new Date(data.timestamp).getMinutes();
		if (!acc[hour]) {
			acc[hour] = {
				count: 1,
				foldTime: data.foldtime,
			};
		}
		acc[hour].count += 1;
		acc[hour].foldTime += data.foldtime;
		return acc;
	}, {} as Record<number, { count: number; foldTime: number }>);

	const chartData = new Array(60).fill(0).map((_, i) => {
		if (!todayDataPerHour[i])
			return { minute: "Minute " + i, value: 0, foldtime: 0 };
		return {
			minute: "Minute " + i,
			value: todayDataPerHour[i].count,
			foldtime: todayDataPerHour[i].foldTime / todayDataPerHour[i].count,
		};
	});
	return (
		<Card className="w-full max-w-[1200px]">
			<CardHeader>
				<CardTitle>This Hour</CardTitle>
				{/* <CardDescription>January - June 2024</CardDescription> */}
			</CardHeader>
			<CardContent>
				<ChartContainer config={chartConfig}>
					<BarChart accessibilityLayer data={chartData}>
						<CartesianGrid vertical={false} />
						<XAxis
							dataKey="minute"
							tickLine={false}
							tickMargin={10}
							axisLine={false}
							tickFormatter={(value) =>
								value.replace("Minute ", "")
							}
						/>
						<ChartTooltip
							cursor={false}
							content={<ChartTooltipContent indicator="line" />}
						/>
						<Bar
							dataKey="value"
							fill="var(--color-value)"
							radius={4}
						/>
						<Bar
							dataKey="foldtime"
							fill="var(--color-foldtime)"
							radius={4}
						/>
					</BarChart>
				</ChartContainer>
			</CardContent>
		</Card>
	);
}
