"use client";

import {
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer,
} from "recharts";
import type { MonthlySpending } from "@/lib/demo-data";

interface SpendingLineChartProps {
  data: MonthlySpending[];
}

function CustomTooltip({
  active,
  payload,
  label,
}: {
  active?: boolean;
  payload?: Array<{ name: string; value: number; color: string }>;
  label?: string;
}) {
  if (!active || !payload) return null;
  return (
    <div className="rounded-lg border border-gray-700 bg-gray-800 p-3 shadow-xl">
      <p className="mb-2 text-sm font-medium text-gray-300">{label}</p>
      {payload.map((entry) => (
        <p key={entry.name} className="text-sm" style={{ color: entry.color }}>
          {entry.name}: ${entry.value.toFixed(2)}
        </p>
      ))}
    </div>
  );
}

export function SpendingLineChart({ data }: SpendingLineChartProps) {
  return (
    <ResponsiveContainer width="100%" height={350}>
      <LineChart data={data} margin={{ top: 5, right: 30, left: 0, bottom: 5 }}>
        <CartesianGrid strokeDasharray="3 3" stroke="#374151" />
        <XAxis dataKey="month" tick={{ fill: "#9CA3AF", fontSize: 12 }} />
        <YAxis
          tick={{ fill: "#9CA3AF", fontSize: 12 }}
          tickFormatter={(v) => `$${v}`}
        />
        <Tooltip content={<CustomTooltip />} />
        <Legend
          wrapperStyle={{ paddingTop: 16 }}
          formatter={(value) => (
            <span className="text-sm text-gray-300">{value}</span>
          )}
        />
        <Line
          type="monotone"
          dataKey="openai"
          name="OpenAI"
          stroke="#6366F1"
          strokeWidth={2}
          dot={{ fill: "#6366F1", r: 4 }}
          activeDot={{ r: 6 }}
        />
        <Line
          type="monotone"
          dataKey="anthropic"
          name="Anthropic"
          stroke="#F59E0B"
          strokeWidth={2}
          dot={{ fill: "#F59E0B", r: 4 }}
          activeDot={{ r: 6 }}
        />
        <Line
          type="monotone"
          dataKey="other"
          name="Other"
          stroke="#10B981"
          strokeWidth={2}
          dot={{ fill: "#10B981", r: 4 }}
          activeDot={{ r: 6 }}
        />
      </LineChart>
    </ResponsiveContainer>
  );
}
