"use client";

import { CartesianGrid, Line, LineChart, XAxis, YAxis } from "recharts";
import {
  type ChartConfig,
  ChartContainer,
  ChartTooltip,
  ChartTooltipContent,
} from "@/components/ui/chart";

interface TrendLineChartProps {
  categoryKey?: string;
  data: Record<string, string | number>[];
  description?: string;
  series: Array<{ key: string; label: string; color: string }>;
  title?: string;
}

export function TrendLineChart({
  data,
  title,
  description,
  categoryKey = "date",
  series,
}: TrendLineChartProps) {
  const chartConfig = Object.fromEntries(
    series.map((s) => [s.key, { label: s.label, color: s.color }])
  ) satisfies ChartConfig;

  return (
    <div className="my-8 rounded-xl border border-white/10 bg-white/[0.02] p-4 sm:p-6">
      {title && (
        <p className="mb-1 text-center font-semibold text-neutral-300 text-sm">
          {title}
        </p>
      )}
      {description && (
        <p className="mb-4 text-center text-neutral-500 text-xs">
          {description}
        </p>
      )}
      <div className="mb-5 flex flex-wrap items-center justify-center gap-3">
        {series.map((s) => (
          <div
            className="flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.03] px-3 py-1.5"
            key={s.key}
          >
            <span
              className="inline-block h-[3px] w-5 rounded-full"
              style={{ backgroundColor: s.color }}
            />
            <span className="font-medium text-neutral-300 text-xs">
              {s.label}
            </span>
          </div>
        ))}
      </div>
      <ChartContainer className="h-[300px] w-full" config={chartConfig}>
        <LineChart
          accessibilityLayer
          data={data}
          margin={{ top: 10, right: 10, left: 0, bottom: 0 }}
        >
          <CartesianGrid stroke="rgba(255,255,255,0.05)" vertical={false} />
          <XAxis
            axisLine={false}
            dataKey={categoryKey}
            tick={{ fill: "#a3a3a3", fontSize: 11 }}
            tickLine={false}
            tickMargin={8}
          />
          <YAxis
            axisLine={false}
            tick={{ fill: "#737373", fontSize: 11 }}
            tickLine={false}
            width={40}
          />
          <ChartTooltip
            content={<ChartTooltipContent indicator="line" />}
            cursor={{ stroke: "rgba(255,255,255,0.1)" }}
          />
          {series.map((s) => (
            <Line
              activeDot={{ r: 6 }}
              dataKey={s.key}
              dot={{ r: 4, fill: `var(--color-${s.key})` }}
              key={s.key}
              stroke={`var(--color-${s.key})`}
              strokeWidth={2}
              type="monotone"
            />
          ))}
        </LineChart>
      </ChartContainer>
    </div>
  );
}
