"use client"

import { useTranslations } from "next-intl"
import { BarChart3 } from "lucide-react"

import { ChartCardShell } from "@/shared/components/charts/chart-card-shell"
import {
  SimpleBarChart,
  type BarSeries,
} from "@/shared/components/charts/simple-bar-chart"
import type { DataChangeActionStat } from "@/modules/audit/types"

interface DataChangeDistributionChartProps {
  data: DataChangeActionStat[]
}

const ACTION_COLORS: Record<string, string> = {
  create: "hsl(var(--chart-1))",
  update: "hsl(var(--chart-2))",
  delete: "hsl(var(--chart-3))",
}

export function DataChangeDistributionChart({
  data,
}: DataChangeDistributionChartProps): React.ReactNode {
  const t = useTranslations("audit.overview")
  const tableT = useTranslations("audit.filter")

  // 将统计数组转为图表数据（保证 create/update/delete 三列都存在）
  const countByAction: Record<string, number> = { create: 0, update: 0, delete: 0 }
  for (const item of data) {
    countByAction[item.action] = item.count
  }

  const chartData = [
    { action: tableT("create"), count: countByAction.create },
    { action: tableT("update"), count: countByAction.update },
    { action: tableT("delete"), count: countByAction.delete },
  ]

  const bars: BarSeries[] = [
    { dataKey: "count", name: t("distributionChart.title"), color: "hsl(var(--chart-1))" },
  ]

  // 按动作着色
  const cellColors: Record<string, string> = {
    [tableT("create")]: ACTION_COLORS.create,
    [tableT("update")]: ACTION_COLORS.update,
    [tableT("delete")]: ACTION_COLORS.delete,
  }

  const isEmpty = data.length === 0 || data.every((d) => d.count === 0)

  return (
    <ChartCardShell
      title={t("distributionChart.title")}
      description={t("distributionChart.description")}
      icon={BarChart3}
      isEmpty={isEmpty}
      emptyTitle={t("distributionChart.title")}
      emptyDescription={t("distributionChart.empty")}
    >
      <SimpleBarChart
        data={chartData}
        bars={bars}
        xKey="action"
        yAllowDecimals={false}
        yTickFormatter={(v) => String(v)}
        cellColors={cellColors}
      />
    </ChartCardShell>
  )
}
