import { useMemo } from "react";
import CandlestickChart, { type OhlcPoint } from "./CandlestickChart";
import { CHART } from "../lib/chartPalette";

const DRILL_MAS = [{ period: 20, color: CHART.teal, label: "MA20" }];

function nearestBarDate(data: OhlcPoint[], focusDate: string) {
  if (!data.length) return null;
  const exact = data.find((p) => p.date === focusDate);
  if (exact) return exact.date;
  const month = data.find((p) => p.date.startsWith(focusDate.slice(0, 7)));
  if (month) return month.date;
  const target = new Date(focusDate).getTime();
  if (Number.isNaN(target)) return null;
  let best = data[0].date;
  let bestDiff = Infinity;
  for (const p of data) {
    const diff = Math.abs(new Date(p.date).getTime() - target);
    if (diff < bestDiff) {
      bestDiff = diff;
      best = p.date;
    }
  }
  return best;
}

export default function SkillDrillChart({
  data,
  focusDate,
  markerLabel,
  symbol,
}: {
  data: OhlcPoint[];
  focusDate?: string | null;
  markerLabel?: string | null;
  symbol: string;
}) {
  const markers = useMemo(() => {
    if (!focusDate || !data.length) return [];
    const date = nearestBarDate(data, focusDate);
    if (!date) return [];
    return [{ date, type: "watch" as const, label: markerLabel || "EP 情境" }];
  }, [data, focusDate, markerLabel]);

  if (!data.length) return null;

  return (
    <div className="skill-drill-chart-wrap">
      <div className="skill-drill-chart-meta pixel">{symbol} · 近一年日 K（教學用）</div>
      <CandlestickChart
        data={data}
        mas={DRILL_MAS}
        showVolume={false}
        markers={markers}
        focusDate={focusDate}
        heightClass="skill-drill-candle"
      />
    </div>
  );
}