import {
  Line,
  LineChart,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from "recharts";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from "../../../shared/ui/card";
import type { AudioSample } from "../../../entities/audioSample/model/types";
import { formatTimeHHMMSS } from "../../../shared/lib/time";

type Props = {
  history: AudioSample[];
};

type ChartPoint = {
  timeMs: number;
  freq_hz: number;
};

export function FrequencyHistoryChart({ history }: Props) {
  const data: ChartPoint[] = history.map((s) => ({
    timeMs: s.timeMs,
    freq_hz: s.freq_hz,
  }));

  return (
    <Card>
      <CardHeader className="pb-2">
        <CardTitle className="text-base">Frequency (last 60s)</CardTitle>
      </CardHeader>
      <CardContent>
        <div className="h-56 w-full">
          <ResponsiveContainer width="100%" height="100%">
            <LineChart
              data={data}
              margin={{ top: 10, right: 12, left: 0, bottom: 0 }}
            >
              <XAxis
                dataKey="timeMs"
                type="number"
                domain={["dataMin", "dataMax"]}
                tickFormatter={(v) => formatTimeHHMMSS(Number(v))}
                tick={{ fontSize: 12 }}
              />
              <YAxis domain={[20, 8000]} tick={{ fontSize: 12 }} width={44} />
              <Tooltip
                labelFormatter={(v) => formatTimeHHMMSS(Number(v))}
                formatter={(v) => [`${Number(v).toFixed(0)} Hz`, "freq"]}
              />
              <Line
                type="monotone"
                dataKey="freq_hz"
                stroke="hsl(var(--primary))"
                strokeWidth={2}
                dot={false}
                isAnimationActive={false}
              />
            </LineChart>
          </ResponsiveContainer>
        </div>
      </CardContent>
    </Card>
  );
}
