"use client";
import { enUS, it } from "date-fns/locale";
import { CalendarIcon } from "lucide-react";
import * as React from "react";
import type { DateRange } from "react-day-picker";
import { Bar, BarChart, CartesianGrid, XAxis } from "recharts";
import { Button } from "~/components/ui/button";
import { Calendar } from "~/components/ui/calendar";
import {
	Card,
	CardAction,
	CardContent,
	CardDescription,
	CardFooter,
	CardHeader,
	CardTitle,
} from "~/components/ui/card";
import {
	type ChartConfig,
	ChartContainer,
	ChartTooltip,
	ChartTooltipContent,
} from "~/components/ui/chart";
import {
	Popover,
	PopoverContent,
	PopoverTrigger,
} from "~/components/ui/popover";
import { cn } from "~/lib/utils";
import { useTranslation } from "~/providers/I18nProvider";

const chartConfig = {
	valueA: {
		color: "var(--chart-2)",
		label: "valueA",
	},
	valueB: {
		color: "var(--chart-3)",
		label: "valueB",
	},
} satisfies ChartConfig;

export type StackedTimeserie = { date: Date; valueA: number; valueB: number };

type AnalyticsChartProps = {
	title: string;
	description?: string;
	valueALabel: string;
	valueBLabel: string;
	timeserie: StackedTimeserie[];
};
export default function TimeserieBarChartStacked({
	timeserie,
	title,
	valueALabel,
	valueBLabel,
	description,
}: AnalyticsChartProps) {
	const { locale } = useTranslation();

	const configs = chartConfig;
	configs.valueA.label = valueALabel;
	configs.valueB.label = valueBLabel;

	const startDate = timeserie[0]
		? new Date(timeserie[0].date)
		: new Date(2025, 1, 1);
	const endDate = timeserie[timeserie.length - 1]
		? // biome-ignore lint/style/noNonNullAssertion: <exists>
			new Date(timeserie[timeserie.length - 1]!.date)
		: new Date();

	const [range, setRange] = React.useState<DateRange | undefined>({
		from: startDate,
		to: endDate,
	});
	const filteredData = React.useMemo(() => {
		if (!range?.from && !range?.to) {
			return timeserie;
		}

		return timeserie.filter((item) => {
			// biome-ignore lint/style/noNonNullAssertion: <exists>
			return item.date >= range.from! && item.date <= range.to!;
		});
	}, [range]);

	const DatePickerLocale = locale === "it" ? it : enUS;

	return (
		<Card className="@container/card w-full pb-4">
			<CardHeader className="flex @md/card:grid flex-col border-b">
				<CardTitle>{title}</CardTitle>
				<CardDescription className={cn(!description && "sr-only")}>
					{description || "Analytics for the selected period."}
				</CardDescription>
				<CardAction className="@md/card:mt-0 mt-2">
					<Popover>
						<PopoverTrigger asChild>
							<Button variant="outline">
								<CalendarIcon />
								{range?.from && range?.to
									? `${range.from.toLocaleDateString()} - ${range.to.toLocaleDateString()}`
									: "Seleziona un intervallo di date"}
							</Button>
						</PopoverTrigger>
						<PopoverContent align="end" className="w-auto overflow-hidden p-0">
							<Calendar
								className="w-full"
								defaultMonth={range?.from}
								fixedWeeks
								locale={DatePickerLocale}
								mode="range"
								onSelect={setRange}
								selected={range}
								showOutsideDays
							/>
						</PopoverContent>
					</Popover>
				</CardAction>
			</CardHeader>
			<CardContent className="px-4">
				<ChartContainer
					className="aspect-auto h-62.5 w-full"
					config={chartConfig}
				>
					{filteredData.length === 0 ? (
						<div className="flex h-full items-center justify-center text-base text-muted-foreground">
							Nessun dato disponibile per il periodo selezionato.
						</div>
					) : (
						<BarChart
							accessibilityLayer
							data={filteredData}
							margin={{
								left: 12,
								right: 12,
							}}
						>
							<CartesianGrid vertical={false} />
							<XAxis
								axisLine={false}
								dataKey="date"
								minTickGap={20}
								tickFormatter={(value) => {
									const date = new Date(String(value));
									return date.toLocaleDateString("it-IT", {
										day: "numeric",
										month: "short",
									});
								}}
								tickLine={false}
								tickMargin={8}
							/>
							<ChartTooltip content={<ChartTooltipContent hideLabel />} />
							<Bar
								dataKey="valueA"
								fill={`var(--color-valueA)`}
								radius={[0, 0, 4, 4]}
								stackId="a"
							/>
							<Bar
								dataKey="valueB"
								fill={`var(--color-valueB)`}
								radius={[4, 4, 0, 0]}
								stackId="a"
							/>
						</BarChart>
					)}
				</ChartContainer>
			</CardContent>
			<CardFooter className="flex justify-end border-t pt-4!">
				<span className="text-muted-foreground text-sm">
					Totale: <strong>{filteredData.reduce((acc) => acc + 1, 0)}</strong>
				</span>
			</CardFooter>
		</Card>
	);
}
