import {
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer,
  TooltipProps,
} from "recharts";
import { PerformanceSummaryData } from "@/types/performance-summary";
import { formatNumber } from "@/lib/common";
import { LINE_CHART_COLORS, prepareChartData } from "@/utils/performance-summary-utils";

type LineTooltipEntry = {
  name: string;
  value: number;
  color?: string;
};

type CustomLineTooltipProps = TooltipProps<number, string> & {
  payload?: LineTooltipEntry[];
  label?: string;
};

const CustomLineTooltip = ({
  active,
  payload,
  label,
}: CustomLineTooltipProps) => {
  if (active && payload && payload.length) {
    return (
      <div className="rounded-lg border border-slate-200 bg-white p-3 shadow-lg">
        <p className="mb-2 font-semibold text-slate-900">{label}</p>
        {payload.map((entry, index) => (
          <div
            key={index}
            className="flex items-center justify-between gap-4 text-sm"
          >
            <div className="flex items-center gap-2">
              <div
                className="h-3 w-3 rounded-lg"
                style={{ backgroundColor: entry.color }}
              />
              <span className="text-slate-600">{entry.name}</span>
            </div>
            <span className="font-medium text-slate-900">
              {formatNumber(entry.value as number)}
            </span>
          </div>
        ))}
      </div>
    );
  }
  return null;
};

interface PerformanceTimelineChartProps {
  data: PerformanceSummaryData | null;
  visibleSeries: Set<string>;
  onToggleSeries: (seriesId: string) => void;
}

export function PerformanceTimelineChart({
  data,
  visibleSeries,
  onToggleSeries,
}: PerformanceTimelineChartProps) {
  const chartData = prepareChartData(data, visibleSeries);

  return (
    <div className="flex flex-col rounded-lg border border-slate-200 bg-white p-6 shadow-sm lg:col-span-2">
      <h3 className="mb-4 text-lg font-semibold text-slate-900">
        Performance Timeline
      </h3>

      <div className="mb-4 flex flex-wrap gap-2">
        {(data?.serialize_array ?? []).map((series) => (
          <button
            key={series.id}
            onClick={() => onToggleSeries(series.id)}
            className={`rounded-lg px-3 py-1.5 text-xs font-medium transition-all duration-200 ${
              visibleSeries.has(series.id)
                ? "bg-[#428B4D] text-white shadow-sm"
                : "bg-slate-100 text-slate-600 hover:bg-slate-200"
            }`}
          >
            {series.name}
          </button>
        ))}
      </div>

      <div className="flex-1" style={{ minHeight: "400px" }}>
        <ResponsiveContainer width="100%" height={400}>
          <LineChart
            data={chartData}
            margin={{ top: 5, right: 5, left: 25, bottom: 5 }}
          >
            <CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" />
            <XAxis dataKey="date" tick={{ fontSize: 12 }} stroke="#64748b" />
            <YAxis
              tick={{ fontSize: 11 }}
              stroke="#64748b"
              tickFormatter={(value) => formatNumber(value)}
            />
            <Tooltip content={<CustomLineTooltip />} />
            <Legend wrapperStyle={{ fontSize: "12px" }} iconType="circle" />
            {(data?.serialize_array ?? [])
              .filter((series) => visibleSeries.has(series.id))
              .map((series, index) => (
                <Line
                  key={series.id}
                  type="monotone"
                  dataKey={series.id}
                  name={series.name}
                  stroke={LINE_CHART_COLORS[index % LINE_CHART_COLORS.length]}
                  strokeWidth={2}
                  dot={false}
                  activeDot={{ r: 6 }}
                />
              ))}
          </LineChart>
        </ResponsiveContainer>
      </div>
    </div>
  );
}
