"use client";

import type { ApexOptions } from "apexcharts";
import { useTheme } from "next-themes";
import { DashboardChart } from "@/components/shared/chart";
import type { InvestmentPortfolio } from "./contract";
import { money } from "./display";

const monthLabel = new Intl.DateTimeFormat("en-GB", {
  month: "short",
  year: "numeric",
  timeZone: "UTC",
});
const axisNumber = new Intl.NumberFormat("en", {
  notation: "compact",
  maximumFractionDigits: 1,
});

export function RevenueChart({ portfolio }: { portfolio: InvestmentPortfolio }) {
  const { resolvedTheme } = useTheme();
  const dark = resolvedTheme === "dark";
  const rows = portfolio.monthly_revenue;
  const investment = portfolio.total_investment;
  const colors = [
    dark ? "#93c5fd" : "#1d4ed8",
    dark ? "#fbbf24" : "#a95512",
    dark ? "#6ee7b7" : "var(--chart-1)",
  ];
  const series = [
    { name: "Gross revenue", data: rows.map((row) => row.gross_revenue) },
    { name: "Energy bill", data: rows.map((row) => row.energy_bill) },
    { name: "Net revenue", data: rows.map((row) => row.net_revenue) },
  ];
  const options: ApexOptions = {
    chart: {
      fontFamily: "inherit",
      foreColor: "var(--muted-foreground)",
      background: "transparent",
      toolbar: { show: false },
      zoom: { enabled: false },
      animations: { enabled: false },
      accessibility: {
        enabled: true,
        description: `Monthly gross revenue, energy bill and net revenue in ${portfolio.currency}. The break-even reference is ${money(investment, portfolio.currency)}.`,
      },
    },
    theme: { mode: dark ? "dark" : "light" },
    colors,
    stroke: { curve: "straight", width: [3, 3, 3], dashArray: [0, 7, 3] },
    markers: { size: rows.length === 1 ? 5 : 0, hover: { size: 6 } },
    dataLabels: { enabled: false },
    grid: { borderColor: "var(--border)", strokeDashArray: 3 },
    legend: { position: "bottom", fontSize: "12px" },
    xaxis: {
      categories: rows.map((row) => monthLabel.format(new Date(`${row.month}-01T00:00:00Z`))),
      tickPlacement: "between",
      labels: { rotate: -45, hideOverlappingLabels: true },
    },
    yaxis: {
      min: (min) => Math.min(0, min),
      max: (max) => Math.max(1, max, investment) * 1.1,
      labels: { formatter: (value) => axisNumber.format(value) },
    },
    annotations: {
      yaxis: [{
        y: investment,
        borderColor: "var(--foreground)",
        borderWidth: 2,
        strokeDashArray: 6,
      }],
    },
    tooltip: {
      shared: true,
      intersect: false,
      y: { formatter: (value) => money(value, portfolio.currency) },
      theme: dark ? "dark" : "light",
    },
  };

  return (
    <div className="chart-container min-w-0 px-2 pb-3 sm:px-4">
      <DashboardChart type="line" height={355} series={series} options={options} />
    </div>
  );
}
