"use client"

import { useMemo } from "react"
import { useTranslations } from "next-intl"
import { TrendingUp } from "lucide-react"

import { ChartCardShell } from "@/shared/components/charts/chart-card-shell"
import { TrendLineChart, type TrendLineSeries } from "@/shared/components/charts/trend-line-chart"
import type { AuditTrendPoint } from "@/modules/audit/types"

interface AuditActivityTrendChartProps {
  data: AuditTrendPoint[]
}

export function AuditActivityTrendChart({ data }: AuditActivityTrendChartProps): React.ReactNode {
  const t = useTranslations("audit.overview")

  const series: TrendLineSeries[] = [
    { dataKey: "auditEvents", name: t("trendChart.auditEvents"), color: "hsl(var(--chart-1))" },
    { dataKey: "loginEvents", name: t("trendChart.loginEvents"), color: "hsl(var(--chart-2))" },
    { dataKey: "dataChanges", name: t("trendChart.dataChanges"), color: "hsl(var(--chart-3))" },
  ]

  // 仅取 MM-DD 部分作为 X 轴标签
  const chartData = useMemo(
    () =>
      data.map((p) => ({
        ...p,
        title: p.date.slice(5),
        fullTitle: p.date,
      })),
    [data],
  )

  // 根据数据最大值计算 Y 轴上界（至少为 10，避免全 0 时域为 [0,0]）
  const yDomain = useMemo<[number, number]>(() => {
    const maxVal = data.reduce(
      (max, p) => Math.max(max, p.auditEvents, p.loginEvents, p.dataChanges),
      0,
    )
    return [0, Math.max(10, maxVal)]
  }, [data])

  const isEmpty = data.every(
    (p) => p.auditEvents === 0 && p.loginEvents === 0 && p.dataChanges === 0,
  )

  return (
    <ChartCardShell
      title={t("trendChart.title")}
      description={t("trendChart.description")}
      icon={TrendingUp}
      isEmpty={isEmpty}
      emptyTitle={t("trendChart.title")}
      emptyDescription={t("trendChart.description")}
    >
      <TrendLineChart
        data={chartData}
        series={series}
        xKey="title"
        yDomain={yDomain}
        yTickFormatter={(v) => String(v)}
        tooltipLabelKey="fullTitle"
      />
    </ChartCardShell>
  )
}
