"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: {
		label: "valueA",
		color: "var(--chart-2)",
	},
	valueB: {
		label: "valueB",
		color: "var(--chart-3)",
	},
} 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 flex-col border-b @md/card:grid">
				<CardTitle>{title}</CardTitle>
				<CardDescription className={cn(!description && "sr-only")}>
					{description || "Analytics for the selected period."}
				</CardDescription>
				<CardAction className="mt-2 @md/card:mt-0">
					<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 className="w-auto overflow-hidden p-0" align="end">
							<Calendar
								className="w-full"
								locale={DatePickerLocale}
								mode="range"
								defaultMonth={range?.from}
								selected={range}
								onSelect={setRange}
								fixedWeeks
								showOutsideDays
							/>
						</PopoverContent>
					</Popover>
				</CardAction>
			</CardHeader>
			<CardContent className="px-4">
				<ChartContainer
					config={chartConfig}
					className="aspect-auto h-[250px] w-full"
				>
					{filteredData.length === 0 ? (
						<div className="text-muted-foreground flex h-full items-center justify-center text-base">
							Nessun dato disponibile per il periodo selezionato.
						</div>
					) : (
						<BarChart
							accessibilityLayer
							data={filteredData}
							margin={{
								left: 12,
								right: 12,
							}}
						>
							<CartesianGrid vertical={false} />
							<XAxis
								dataKey="date"
								tickLine={false}
								axisLine={false}
								tickMargin={8}
								minTickGap={20}
								tickFormatter={(value) => {
									const date = new Date(String(value));
									return date.toLocaleDateString("it-IT", {
										day: "numeric",
										month: "short",
									});
								}}
							/>
							<ChartTooltip content={<ChartTooltipContent hideLabel />} />
							<Bar
								stackId="a"
								dataKey="valueA"
								fill={`var(--color-valueA)`}
								radius={[0, 0, 4, 4]}
							/>
							<Bar
								stackId="a"
								dataKey="valueB"
								fill={`var(--color-valueB)`}
								radius={[4, 4, 0, 0]}
							/>
						</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>
	);
}
