"use client";

import React, { useMemo } from "react";
import { AgCharts } from "ag-charts-react";
import { AgChartOptions } from "ag-charts-community";

interface BarData {
  category: string;
  value: number;
  color?: string;
}

interface RevenueChartProps {
  data: BarData[];
  title?: string;
}

export function RevenueChart({
  data,
  title = "Monthly Revenue",
}: RevenueChartProps) {
  const chartOptions: AgChartOptions = useMemo(
    () => ({
      title: {
        text: title,
        fontSize: 18,
        fontWeight: "bold",
      },
      data,
      series: [
        {
          type: "bar",
          xKey: "category",
          yKey: "value",
          fills: data.map((item) => item.color || "#10b981"),
          strokes: ["#ffffff"],
          strokeWidth: 2,
          cornerRadius: 4,
          highlightStyle: {
            item: {
              fill: "#059669",
              stroke: "#ffffff",
              strokeWidth: 2,
            },
          },
          label: {
            enabled: true,
            position: "top",
            fontSize: 12,
            fontWeight: "bold",
            color: "#374151",
            formatter: (params: any) => `$${params.value.toLocaleString()}`,
          },
          tooltip: {
            enabled: true,
            renderer: (params: any) => {
              return `<div class="bg-white p-2 rounded shadow-lg border">
              <div class="font-bold">${params.datum.category}</div>
              <div class="text-sm">Revenue: $${params.datum.value.toLocaleString()}</div>
            </div>`;
            },
          },
        },
      ],
      axes: [
        {
          type: "category",
          position: "bottom",
          title: {
            text: "Month",
            fontSize: 14,
          },
          label: {
            fontSize: 12,
            rotation: 45,
          },
        },
        {
          type: "number",
          position: "left",
          title: {
            text: "Revenue ($)",
            fontSize: 14,
          },
          label: {
            fontSize: 12,
            formatter: (params: any) => `$${params.value.toLocaleString()}`,
          },
        },
      ],
      legend: {
        enabled: false,
      },
      padding: {
        top: 20,
        right: 20,
        bottom: 60,
        left: 80,
      },
    }),
    [data, title],
  );

  return <AgCharts options={chartOptions} />;
}
