"use client";

import { useState } from "react";
import { formatPaise } from "@/lib/format";

type Day = { date: string; messages: number; charged_paise: number; estimated_paise: number; free: number };
const dayLabel = (d: string) => new Date(`${d}T00:00:00Z`).toLocaleDateString("en-IN", { day: "numeric", month: "short", timeZone: "UTC" });

/**
 * Daily template messages (one series, one hue). Bars are anchored to the baseline with rounded tops and a
 * 2px gap; hovering or focusing a day shows its messages, confirmed charges, pending estimates and free sends.
 */
export function UsageChart({ days }: { days: Day[] }) {
  const [hover, setHover] = useState<number | null>(null);
  const max = Math.max(1, ...days.map((d) => d.messages));
  // Round up to a step that keeps the midpoint gridline on a distinct whole number (2, 4, ... then multiples of 10).
  const step = max > 10 ? 10 : 2;
  const top = Math.max(step, Math.ceil(max / step) * step);
  const h = 160;
  const d = hover !== null ? days[hover] : null;
  return (
    <div>
      <div className="mb-2 flex h-10 items-end justify-between gap-3 text-sm">
        {d ? (
          <p className="tabular">
            <span className="font-medium">{dayLabel(d.date)}</span>
            <span className="text-muted">
              : {d.messages} messages, {formatPaise(d.charged_paise)} charged
              {d.estimated_paise ? `, ${formatPaise(d.estimated_paise)} pending` : ""}
              {d.free ? `, ${d.free} free` : ""}
            </span>
          </p>
        ) : (
          <p className="text-muted">Template messages per day. Hover a day for details.</p>
        )}
      </div>
      <div className="relative" style={{ height: h }}>
        {[0, 0.5, 1].map((f) => (
          <div key={f} className="absolute inset-x-0 border-t border-line/70" style={{ bottom: f * h }}>
            <span className="tabular absolute -top-2.5 right-full mr-2 text-[11px] text-muted">{Math.round(top * f)}</span>
          </div>
        ))}
        <div className="absolute inset-0 ml-0 flex items-end gap-[2px]" role="img" aria-label={`Template messages per day for the last ${days.length} days`}>
          {days.map((day, i) => (
            <button
              key={day.date}
              type="button"
              aria-label={`${dayLabel(day.date)}: ${day.messages} messages, ${formatPaise(day.charged_paise)} charged`}
              onMouseEnter={() => setHover(i)}
              onMouseLeave={() => setHover(null)}
              onFocus={() => setHover(i)}
              onBlur={() => setHover(null)}
              className="group relative flex h-full flex-1 items-end focus:outline-none"
            >
              <span
                className={`block w-full rounded-t-[4px] transition-colors ${hover === i ? "bg-teal-dark" : "bg-teal"} ${day.messages ? "" : "opacity-0"}`}
                style={{ height: `${(day.messages / top) * 100}%`, minHeight: day.messages ? 2 : 0 }}
              />
            </button>
          ))}
        </div>
      </div>
      <div className="mt-1.5 flex justify-between text-[11px] text-muted">
        <span>{days[0] && dayLabel(days[0].date)}</span>
        <span>{days.length > 1 && dayLabel(days[days.length - 1].date)}</span>
      </div>
    </div>
  );
}
