import {
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer,
} from "recharts";
import { SeriesData } from "@/types/portfolio-analytics";
import { formatNumber } from "@/lib/common";
import {
  CHART_COLORS,
  prepareChartData,
  calculateYDomain,
} from "@/utils/portfolio-analytics-utils";

interface PortfolioChartProps {
  series: SeriesData[];
  dateList: string[];
  visibleSeries: Set<string>;
  onToggleSeries: (seriesId: string) => void;
}

export function PortfolioChart({
  series,
  dateList,
  visibleSeries,
  onToggleSeries,
}: PortfolioChartProps) {
  const chartData = prepareChartData(series, dateList, visibleSeries);
  const yDomain = calculateYDomain(chartData);

  // Wrapper function to match tickFormatter signature: (value: any, index: number) => string
  const formatTick = (value: any) => formatNumber(value);

  return (
    <div className="mb-6 rounded-lg border border-gray-200 bg-white p-6 shadow-sm">
      <h2 className="mb-4 text-center text-lg font-semibold text-slate-900">
        Asset Values Over Time
      </h2>
      <div className="mb-4 flex flex-wrap gap-2">
        {series.map((seriesItem) => (
          <button
            key={seriesItem.id}
            onClick={() => onToggleSeries(seriesItem.id)}
            className={`rounded-lg px-3 py-1.5 text-xs font-medium transition-all ${
              visibleSeries.has(seriesItem.id)
                ? "bg-[#428B4D] text-white shadow-sm"
                : "bg-gray-100 text-gray-600 hover:bg-gray-200"
            }`}
          >
            {seriesItem.name}
          </button>
        ))}
      </div>
      <ResponsiveContainer width="100%" height={400}>
        <LineChart
          data={chartData}
          margin={{ top: 5, right: 30, left: 0, bottom: 5 }}
        >
          <CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" />
          <XAxis dataKey="date" tick={{ fontSize: 12 }} stroke="#64748b" />
          <YAxis
            domain={yDomain}
            tick={{ fontSize: 12 }}
            stroke="#64748b"
            tickFormatter={formatTick}
            tickCount={5}
          />
          <Tooltip
            formatter={(value: any) =>
              new Intl.NumberFormat("en-US", {
                minimumFractionDigits: 2,
                maximumFractionDigits: 2,
              }).format(value)
            }
            labelFormatter={(label) => `Date: ${label}`}
            contentStyle={{
              backgroundColor: "#fff",
              border: "1px solid #e2e8f0",
              borderRadius: "8px",
            }}
          />
          <Legend wrapperStyle={{ fontSize: "12px" }} iconType="circle" />
          {series
            .filter((s) => visibleSeries.has(s.id))
            .map((seriesItem, i) => (
              <Line
                key={seriesItem.id}
                type="monotone"
                dataKey={seriesItem.id}
                name={seriesItem.name}
                stroke={CHART_COLORS[i % CHART_COLORS.length]}
                strokeWidth={2}
                dot={{ r: 4 }}
                activeDot={{ r: 6 }}
              />
            ))}
        </LineChart>
      </ResponsiveContainer>
    </div>
  );
}
