"use client";
import { formatHoursMinutes } from "@/features/shared/clientReviewPolicy";

import { hourUnitForDisplay } from "../leaderboardValue";
import { chartHoursScale } from "../chartHoursScale";
import { useState } from "react";
import { barchartStyles } from "./barchartStyles";
import { useTranslation } from "react-i18next";

export default function Barchart({
  data,
}: {
  /* `year` is a **number**: `/statistics/` builds the series from
     `range($currentYear, $currentYear + 6)` and emits each year as an int. */
  data: { year: number; total_hours: number }[];
}) {
  const { t } = useTranslation();
  const [hoverIndex, setHoverIndex] = useState<number | null>(null);

  if (!data || !Array.isArray(data)) {
    return (
      <div
        style={{
          fontFamily: "Cairo, sans-serif",
          padding: "28px 20px",
          margin: "0 auto",
          boxShadow: "0px 4px 4px 0px #00000040",
          border: "1px solid #CBCBCB",
          borderRadius: "8px",
          backgroundColor: "white",
          textAlign: "center",
          color: "#666",
        }}
      >
        {t("COMMON.NO_DATA_AVAILABLE") || "No data available"}
      </div>
    );
  }

  const sortedData = [...data].sort((a, b) =>
    String(a.year).localeCompare(String(b.year))
  );

  const { maximum: maxHours, ticks: gridLines } = chartHoursScale(sortedData.map(item => item.total_hours));
  const chartHeight = 280;
  const barWidth = 40;


  const chartStyles = barchartStyles({
    chartHeight,
    barWidth,
    barCount: data.length,
  });

  return (
    <div id="style-1" style={chartStyles.container}>
      <h2 style={chartStyles.title}>{t("COMMON.VOLUNTEER.BARCHAR.TTILE")}</h2>

      <div style={chartStyles.chartArea}>
        {gridLines.map((line, index) => (
          <div key={index}>
            {line !== 0 && (
              <div
                style={{
                  ...chartStyles.gridLine,
                  bottom: `${(line / maxHours) * chartHeight}px`,
                }}
              />
            )}
            <div
              style={{
                ...chartStyles.yAxisLabel,
                bottom: `${(line / maxHours) * chartHeight - 6}px`,
              }}
            >
              {line < 1000
                ? String(line)
                : `${line / 1000} ${t("ACHIEVEMENTS.THOUSAND")}`}
            </div>
          </div>
        ))}

        <div style={chartStyles.barsContainer}>
          {sortedData?.map((item, index) => (
            <div
              key={index}
              style={chartStyles.barContainer}
              onMouseEnter={() => setHoverIndex(index)}
              onMouseLeave={() => setHoverIndex(null)}
            >
              {hoverIndex === index && (
                <div style={chartStyles.tooltip}>
                  {formatHoursMinutes(item.total_hours)} {hourUnitForDisplay(formatHoursMinutes(item.total_hours), t)}
                </div>
              )}

              <div
                style={{
                  ...chartStyles.bar,
                  height: `${(item.total_hours / maxHours) * chartHeight}px`,
                }}
              />

              <div style={chartStyles.xAxisLabel}>{item.year}</div>

              {/* The hours were readable only by hovering the bar, so the
                  chart was pointer-only — the axes give the year and the
                  scale, and nothing exposed a bar's value. Published to the
                  accessibility tree instead of emulating the hover, with no
                  visual change. */}
              <span className="sr-only">
                {`${item.year}: ${formatHoursMinutes(item.total_hours)} ${hourUnitForDisplay(formatHoursMinutes(item.total_hours), t)}`}
              </span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}
