"use client";

import { useRef, useEffect, useState } from "react";
import {
  RadarChart,
  PolarGrid,
  PolarAngleAxis,
  Radar,
  Tooltip,
} from "recharts";
import type { SkillEntry } from "@capakraken/shared";

interface Props {
  skills: SkillEntry[];
}

export function SkillRadarChart({ skills }: Props) {
  const containerRef = useRef<HTMLDivElement>(null);
  const [width, setWidth] = useState(0);

  useEffect(() => {
    const el = containerRef.current;
    if (!el) return;
    const ro = new ResizeObserver(([entry]) => {
      if (entry) setWidth(entry.contentRect.width);
    });
    ro.observe(el);
    setWidth(el.getBoundingClientRect().width);
    return () => ro.disconnect();
  }, []);

  if (skills.length === 0) {
    return (
      <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-5">
        <h2 className="text-sm font-semibold text-gray-800 dark:text-gray-100 mb-4">Skill Profile</h2>
        <div className="flex items-center justify-center h-48 text-sm text-gray-400 dark:text-gray-500">
          No skills recorded yet
        </div>
      </div>
    );
  }

  const categoryMap = new Map<string, number[]>();
  for (const s of skills) {
    const cat = s.category ?? "Other";
    if (!categoryMap.has(cat)) categoryMap.set(cat, []);
    categoryMap.get(cat)!.push(s.proficiency);
  }

  const data = Array.from(categoryMap.entries())
    .map(([category, profs]) => ({
      category,
      score: Math.round((profs.reduce((a, b) => a + b, 0) / profs.length) * 20),
    }))
    .sort((a, b) => b.score - a.score)
    .slice(0, 8);

  if (data.length < 3) return null;

  return (
    <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-5">
      <h2 className="text-sm font-semibold text-gray-800 dark:text-gray-100 mb-4">Skill Profile</h2>
      <div ref={containerRef} style={{ height: 260 }}>
        {width > 0 && (
          <RadarChart
            width={width}
            height={260}
            data={data}
            margin={{ top: 10, right: 30, bottom: 10, left: 30 }}
          >
            <PolarGrid stroke="#e5e7eb" />
            <PolarAngleAxis
              dataKey="category"
              tick={{ fontSize: 11, fill: "#6b7280" }}
            />
            <Tooltip
              formatter={(value: number | undefined) => [`${value ?? 0}%`, "Avg proficiency"] as [string, string]}
              contentStyle={{ fontSize: 12, borderRadius: 8 }}
            />
            <Radar
              name="Skills"
              dataKey="score"
              stroke="#6366f1"
              fill="#6366f1"
              fillOpacity={0.2}
              strokeWidth={2}
              isAnimationActive={false}
            />
          </RadarChart>
        )}
      </div>
    </div>
  );
}
