"use client"

import {
  Bar,
  BarChart,
  CartesianGrid,
  Cell,
  Legend,
  Pie,
  PieChart,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from "recharts"
import { useTranslations } from "next-intl"

import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Skeleton } from "@/components/ui/skeleton"
import type { ChartSlice } from "@/lib/api/dashboard"
import { chartColor } from "@/lib/chart-colors"
import { topThemeUsageSlices } from "@/lib/api/themes"

type ThemesUsageChartProps = {
  data: ChartSlice[]
  variant?: "pie" | "bar"
  limit?: number
  isLoading?: boolean
  className?: string
}

export function ThemesUsageChart({
  data,
  variant = "pie",
  limit = 10,
  isLoading = false,
  className,
}: ThemesUsageChartProps) {
  const t = useTranslations("Themes.charts")
  const chartData = topThemeUsageSlices(data, limit)

  if (isLoading && data.length === 0) {
    return <Skeleton className={`h-72 w-full ${className ?? ""}`} />
  }

  if (chartData.length === 0) {
    return null
  }

  return (
    <Card className={className}>
      <CardHeader>
        <CardTitle className="font-medium text-sm">{t("usageDistribution")}</CardTitle>
      </CardHeader>
      <CardContent className="h-72">
        <ResponsiveContainer width="100%" height="100%">
          {variant === "bar" ? (
            <BarChart
              data={chartData}
              layout="vertical"
              margin={{ top: 4, right: 12, left: 4, bottom: 4 }}
            >
              <CartesianGrid horizontal={false} strokeDasharray="3 3" />
              <XAxis type="number" tickLine={false} axisLine={false} />
              <YAxis
                type="category"
                dataKey="name"
                width={120}
                tickLine={false}
                axisLine={false}
                tick={{ fontSize: 11 }}
              />
              <Tooltip />
              <Bar dataKey="value" radius={[0, 6, 6, 0]}>
                {chartData.map((_, index) => (
                  <Cell key={index} fill={chartColor(index)} />
                ))}
              </Bar>
            </BarChart>
          ) : (
            <PieChart>
              <Tooltip />
              <Legend />
              <Pie
                data={chartData}
                dataKey="value"
                nameKey="name"
                innerRadius={55}
                outerRadius={90}
              >
                {chartData.map((_, index) => (
                  <Cell key={index} fill={chartColor(index, 1)} />
                ))}
              </Pie>
            </PieChart>
          )}
        </ResponsiveContainer>
      </CardContent>
    </Card>
  )
}
