"use client";
import * as React from "react";
import { CalendarIcon } from "lucide-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,
  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 { enUS, it } from "date-fns/locale";
import { useTranslation } from "~/providers/I18nProvider";

const chartConfig = {
  value: {
    label: "value",
    color: "var(--color-primary)",
  },
} satisfies ChartConfig;

type AnalyticsChartProps = {
  title: string;
  description?: string;
  timeserie: { date: Date; value: number }[];
};
export default function AnalyticsChart({
  timeserie,
  title,
  description,
}: AnalyticsChartProps) {
  const { locale } = useTranslation();

  const startDate = timeserie[0]
    ? new Date(timeserie[0].date)
    : new Date(2025, 1, 1);
  const endDate = timeserie[timeserie.length - 1]
    ? 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) => {
      return item.date >= range.from! && item.date <= range.to!;
    });
  }, [range]);

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

  return (
    <Card className="@container/card w-full">
      <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()}`
                  : "June 2025"}
              </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
                    className="w-[150px]"
                    nameKey="value"
                    labelFormatter={() => "Utenti"}
                  />
                }
              />
              <Bar dataKey="value" fill={`var(--color-value)`} radius={4} />
            </BarChart>
          )}
        </ChartContainer>
      </CardContent>
    </Card>
  );
}
