"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 DayChart({
	data,
}: {
	data: {
		timestamp: number;
		foldtime: number;
	}[];
}) {
	const thisMonthTimestamp = new Date();
	thisMonthTimestamp.setHours(0, 0, 0, 0);
	thisMonthTimestamp.setDate(1);
	const nextMonthTimestamp = new Date();
	nextMonthTimestamp.setHours(0, 0, 0, 0);
	nextMonthTimestamp.setDate(1);
	nextMonthTimestamp.setMonth(nextMonthTimestamp.getMonth() + 1);

	console.log(thisMonthTimestamp.getTime(), nextMonthTimestamp.getTime());

	const thisMonthData = data.filter(
		(data) =>
			data.timestamp >= thisMonthTimestamp.getTime() &&
			data.timestamp < nextMonthTimestamp.getTime()
	);

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

	const thisMonthDays = new Date();
	thisMonthDays.setMonth(thisMonthDays.getMonth() + 1);
	thisMonthDays.setDate(1);
	thisMonthDays.setDate(thisMonthDays.getDate() - 1);

	const chartData = new Array(thisMonthDays.getDate()).fill(0).map((_, i) => {
		const day = i + 1;
		if (!todayDataPerHour[day])
			return { day: "Day " + day, value: 0, foldtime: 0 };
		return {
			day: "Day " + day,
			value: todayDataPerHour[day].count,
			foldtime:
				todayDataPerHour[day].foldTime / todayDataPerHour[day].count,
		};
	});
	return (
		<Card className="w-full max-w-[1200px]">
			<CardHeader>
				<CardTitle>This Month</CardTitle>
				{/* <CardDescription>January - June 2024</CardDescription> */}
			</CardHeader>
			<CardContent>
				<ChartContainer config={chartConfig}>
					<BarChart accessibilityLayer data={chartData}>
						<CartesianGrid vertical={false} />
						<XAxis
							dataKey="day"
							tickLine={false}
							tickMargin={10}
							axisLine={false}
						/>
						<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>
	);
}
