import type { ForecastMonth } from "@/lib/forecast-queries";

function fmtEur(n: number) {
  return n.toLocaleString("it-IT", {
    style: "currency",
    currency: "EUR",
    minimumFractionDigits: 0,
    maximumFractionDigits: 0,
  });
}

export function ForecastChart({ data }: { data: ForecastMonth[] }) {
  const max = Math.max(...data.map((d) => d.total), 1);
  // index 0 = mese corrente, index 1 = mese prossimo (evidenziato)
  const nextMonth = data[1];

  return (
    <div className="bg-white rounded-xl border border-[#e5e7eb] p-6 space-y-5">
      {nextMonth && (
        <div className="flex items-baseline justify-between">
          <div>
            <p className="text-xs font-bold uppercase tracking-wider text-[#71717a]">
              Previsto il mese prossimo
            </p>
            <p className="text-xs text-[#a1a1aa] mt-0.5 capitalize">{nextMonth.label}</p>
          </div>
          <p className="text-2xl font-bold tracking-tight text-[#1A463C]">
            {fmtEur(nextMonth.total)}
          </p>
        </div>
      )}

      <div className="flex items-end gap-2 h-44 border-t border-[#f4f4f5] pt-4">
        {data.map((m, i) => {
          const pct = Math.round((m.total / max) * 100);
          const isNext = i === 1;
          return (
            <div key={`${m.year}-${m.month}`} className="flex-1 flex flex-col items-center gap-1">
              <div className="w-full flex flex-col justify-end" style={{ height: "120px" }}>
                <div
                  className={`w-full rounded-t-md transition-all ${
                    isNext ? "bg-[#1A463C]" : "bg-[#1A463C]/35"
                  }`}
                  style={{ height: `${pct}%`, minHeight: m.total > 0 ? "4px" : "0" }}
                  title={`${m.label}: ${m.total.toLocaleString("it-IT", { style: "currency", currency: "EUR", minimumFractionDigits: 2 })}`}
                />
              </div>
              <span
                className={`text-[10px] capitalize ${
                  isNext ? "font-bold text-[#1A463C]" : "text-[#71717a]"
                }`}
              >
                {m.label.split(" ")[0]}
              </span>
            </div>
          );
        })}
      </div>
    </div>
  );
}
