"use client";

import * as React from "react";
import {
  ResponsiveContainer,
  PieChart,
  Pie,
  Cell,
  Tooltip as RechartsTooltip,
} from "recharts";
import type { ForecastCategory } from "./types";
import { fmtForecastMillions } from "./forecast-format";

type ForecastCategoryChartProps = {
  categories: ForecastCategory[];
  period: string;
};

export function ForecastCategoryChart({
  categories,
  period,
}: ForecastCategoryChartProps) {
  const [activeIndex, setActiveIndex] = React.useState(0);
  const total = categories.reduce((sum, row) => sum + row.val, 0);

  if (categories.length === 0 || total <= 0) {
    return (
      <div className="bg-white rounded-xl border border-border p-6 shadow-sm">
        <h3 className="text-[13px] font-extrabold text-text font-['Lexend'] mb-1">
          Forecast Breakdown
        </h3>
        <p className="text-[11px] text-gray-700 font-medium mb-4 uppercase tracking-tight">
          Weighted pipeline · {period}
        </p>
        <p className="text-sm text-gray-600">No pipeline forecast data yet.</p>
      </div>
    );
  }

  const active = categories[activeIndex] ?? categories[0];
  const activePct = total > 0 ? ((active.val / total) * 100).toFixed(1) : "0";

  return (
    <div className="bg-white rounded-xl border border-border p-6 shadow-sm flex flex-col min-h-[320px]">
      <h3 className="text-[13px] font-extrabold text-text font-['Lexend'] mb-1">
        Forecast Breakdown
      </h3>
      <p className="text-[11px] text-gray-700 font-medium mb-4 uppercase tracking-tight">
        Weighted pipeline · {period}
      </p>

      <div className="relative h-[180px] shrink-0">
        <ResponsiveContainer width="100%" height="100%">
          <PieChart>
            <Pie
              data={categories}
              dataKey="val"
              nameKey="name"
              innerRadius={52}
              outerRadius={76}
              paddingAngle={2}
              stroke="none"
              onMouseEnter={(_, index) => setActiveIndex(index)}
            >
              {categories.map((entry) => (
                <Cell key={entry.name} fill={entry.fill} />
              ))}
            </Pie>
            <RechartsTooltip
              contentStyle={{
                borderRadius: "12px",
                border: "none",
                boxShadow: "0 4px 14px rgba(0,0,0,0.15)",
                padding: "10px 12px",
                backgroundColor: "#0F1117",
                color: "#fff",
                fontSize: "12px",
              }}
              formatter={(value: number, name: string) => [
                fmtForecastMillions(value),
                name,
              ]}
            />
          </PieChart>
        </ResponsiveContainer>
        <div className="pointer-events-none absolute inset-0 flex flex-col items-center justify-center text-center">
          <span className="text-[11px] font-bold" style={{ color: active.fill }}>
            {active.name}
          </span>
          <span className="mt-0.5 font-['Lexend'] text-lg font-extrabold text-text">
            {fmtForecastMillions(total)}
          </span>
          <span className="text-[10px] font-semibold text-gray-500">
            {activePct}% · {fmtForecastMillions(active.val)}
          </span>
        </div>
      </div>

      <div className="mt-4 space-y-2 flex-1 overflow-y-auto scrollbar-themed max-h-[120px]">
        {categories.map((f, index) => {
          const pct = total > 0 ? (f.val / total) * 100 : 0;
          return (
            <button
              key={f.name}
              type="button"
              className="w-full rounded-lg border border-gray-100 bg-gray-50/60 px-3 py-2 text-left transition-colors hover:bg-white"
              onMouseEnter={() => setActiveIndex(index)}
            >
              <div className="flex items-center justify-between gap-2 mb-1">
                <div className="flex items-center gap-2 min-w-0">
                  <span
                    className="size-2 rounded-full shrink-0"
                    style={{ backgroundColor: f.fill }}
                  />
                  <span className="text-[11px] font-bold text-gray-700 truncate">
                    {f.name}
                  </span>
                </div>
                <span className="text-[11px] font-extrabold text-text shrink-0">
                  {fmtForecastMillions(f.val)}
                </span>
              </div>
              <div className="h-1 w-full bg-bg rounded-full overflow-hidden">
                <div
                  className="h-full rounded-full transition-all duration-500"
                  style={{ width: `${pct}%`, backgroundColor: f.fill }}
                />
              </div>
            </button>
          );
        })}
      </div>
    </div>
  );
}
