import { useEffect } from "react";
import { useTranslation } from "react-i18next";
import { BarChart3 as BarIcon, AreaChart as AreaIcon } from "lucide-react";
import type { CategoryOverTimeChartType } from "./CategoryOverTimeChart";

export const TRENDS_CHART_TYPE_STORAGE_KEY = "reports-trends-category-charttype";

export interface TrendsChartTypeToggleProps {
  value: CategoryOverTimeChartType;
  onChange: (value: CategoryOverTimeChartType) => void;
  /** localStorage key used to persist the preference. */
  storageKey?: string;
}

export function readTrendsChartType(
  storageKey: string = TRENDS_CHART_TYPE_STORAGE_KEY,
  fallback: CategoryOverTimeChartType = "bar",
): CategoryOverTimeChartType {
  if (typeof localStorage === "undefined") return fallback;
  const saved = localStorage.getItem(storageKey);
  // Back-compat: "line" was the historical key for the bar chart.
  if (saved === "line") return "bar";
  return saved === "bar" || saved === "area" ? saved : fallback;
}

export default function TrendsChartTypeToggle({
  value,
  onChange,
  storageKey = TRENDS_CHART_TYPE_STORAGE_KEY,
}: TrendsChartTypeToggleProps) {
  const { t } = useTranslation();

  useEffect(() => {
    if (storageKey) localStorage.setItem(storageKey, value);
  }, [value, storageKey]);

  const options: { type: CategoryOverTimeChartType; icon: React.ReactNode; label: string }[] = [
    { type: "bar", icon: <BarIcon size={14} />, label: t("reports.trends.chartBar") },
    { type: "area", icon: <AreaIcon size={14} />, label: t("reports.trends.chartArea") },
  ];

  return (
    <div className="inline-flex gap-1" role="group" aria-label={t("reports.trends.chartTypeAria")}>
      {options.map(({ type, icon, label }) => (
        <button
          key={type}
          type="button"
          onClick={() => onChange(type)}
          aria-pressed={value === type}
          className={`inline-flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm font-medium transition-colors ${
            value === type
              ? "bg-[var(--primary)] text-white"
              : "bg-[var(--card)] border border-[var(--border)] text-[var(--foreground)] hover:bg-[var(--muted)]"
          }`}
        >
          {icon}
          {label}
        </button>
      ))}
    </div>
  );
}
