"use client";

import {
  CartesianGrid,
  Legend,
  Line,
  LineChart,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from "recharts";

export type DailyRow = {
  date: string;
  impressions: number;
  clicks: number;
  leads: number;
  spentCents: number;
};

export function SelfServeAnalyticsChart({ data }: { data: DailyRow[] }) {
  const rows = data.map((d) => ({
    ...d,
    spentRsd: d.spentCents / 100,
  }));

  function exportCsv() {
    const header = "datum,prikazi,klikovi,upiti,potroseno_rsd";
    const lines = rows.map(
      (r) =>
        `${r.date},${r.impressions},${r.clicks},${r.leads},${r.spentRsd.toFixed(
          2
        )}`
    );
    const blob = new Blob([[header, ...lines].join("\n")], {
      type: "text/csv;charset=utf-8;",
    });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = "analitika-kampanje.csv";
    a.click();
    URL.revokeObjectURL(url);
  }

  return (
    <div className="space-y-4">
      <div className="flex justify-end">
        <button
          onClick={exportCsv}
          className="rounded-lg border border-black/15 px-4 py-2 text-sm font-medium hover:bg-black/5"
        >
          Izvezi CSV
        </button>
      </div>
      <div
        className="h-[320px] w-full"
        style={{ fontFamily: "Manrope, sans-serif" }}
      >
        <ResponsiveContainer width="100%" height="100%">
          <LineChart data={rows}>
            <CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
            <XAxis dataKey="date" fontSize={11} />
            <YAxis fontSize={11} />
            <Tooltip />
            <Legend />
            <Line
              type="monotone"
              dataKey="impressions"
              name="Prikazi"
              stroke="#94a3b8"
            />
            <Line
              type="monotone"
              dataKey="clicks"
              name="Klikovi"
              stroke="#c2410c"
            />
            <Line
              type="monotone"
              dataKey="leads"
              name="Upiti"
              stroke="#16a34a"
            />
          </LineChart>
        </ResponsiveContainer>
      </div>
    </div>
  );
}
