"use client";

import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  Tooltip,
  ResponsiveContainer,
  CartesianGrid,
} from "recharts";

interface VesselData {
  name: string;
  amount: number;
}

interface MonthData {
  month: string;
  amount: number;
}

interface Props {
  vesselData: VesselData[];
  monthData: MonthData[];
}

function currencyTick(value: number): string {
  if (value >= 1_000_000) return `₹${(value / 1_000_000).toFixed(1)}M`;
  if (value >= 1_000) return `₹${(value / 1_000).toFixed(0)}K`;
  return `₹${value}`;
}

function currencyTooltip(value: number): string {
  return value.toLocaleString("en-IN", { style: "currency", currency: "INR", maximumFractionDigits: 0 });
}

export function SpendCharts({ vesselData, monthData }: Props) {
  return (
    <div className="mt-8 grid grid-cols-1 gap-6 lg:grid-cols-2">
      {vesselData.length > 0 && (
        <div className="rounded-lg border border-neutral-200 bg-white p-5">
          <h2 className="text-sm font-semibold text-neutral-700 mb-4">Approved Spend by Cost Centre (Top 5)</h2>
          <ResponsiveContainer width="100%" height={220}>
            <BarChart data={vesselData} margin={{ top: 4, right: 8, bottom: 4, left: 8 }}>
              <CartesianGrid strokeDasharray="3 3" stroke="#f0f0f0" vertical={false} />
              <XAxis dataKey="name" tick={{ fontSize: 11 }} tickLine={false} axisLine={false} />
              <YAxis tickFormatter={currencyTick} tick={{ fontSize: 11 }} tickLine={false} axisLine={false} width={60} />
              <Tooltip formatter={(v) => [currencyTooltip(Number(v)), "Spend"]} cursor={{ fill: "#f5f5f5" }} />
              <Bar dataKey="amount" fill="#4f46e5" radius={[4, 4, 0, 0]} />
            </BarChart>
          </ResponsiveContainer>
        </div>
      )}

      {monthData.length > 0 && (
        <div className="rounded-lg border border-neutral-200 bg-white p-5">
          <h2 className="text-sm font-semibold text-neutral-700 mb-4">Approved Spend by Month</h2>
          <ResponsiveContainer width="100%" height={220}>
            <BarChart data={monthData} margin={{ top: 4, right: 8, bottom: 4, left: 8 }}>
              <CartesianGrid strokeDasharray="3 3" stroke="#f0f0f0" vertical={false} />
              <XAxis dataKey="month" tick={{ fontSize: 11 }} tickLine={false} axisLine={false} />
              <YAxis tickFormatter={currencyTick} tick={{ fontSize: 11 }} tickLine={false} axisLine={false} width={60} />
              <Tooltip formatter={(v) => [currencyTooltip(Number(v)), "Spend"]} cursor={{ fill: "#f5f5f5" }} />
              <Bar dataKey="amount" fill="#0ea5e9" radius={[4, 4, 0, 0]} />
            </BarChart>
          </ResponsiveContainer>
        </div>
      )}
    </div>
  );
}
