import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import BudgetVsActualTable from "./BudgetVsActualTable";
import { getBudgetVsActualData } from "../../services/budgetService";
import type { BudgetVsActualRow } from "../../shared/types";

export interface CompareBudgetViewProps {
  year: number;
  month: number;
  /** Account (import source) filter — forwarded to getBudgetVsActualData so this
   * sub-tab respects the same FilterPanel selection as the rest of the Compare
   * page (Issue #276). Empty/omitted = no filter. */
  accountIds?: number[];
}

export default function CompareBudgetView({ year, month, accountIds }: CompareBudgetViewProps) {
  const { t } = useTranslation();
  const [rows, setRows] = useState<BudgetVsActualRow[]>([]);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    let cancelled = false;
    setError(null);
    getBudgetVsActualData(year, month, accountIds)
      .then((data) => {
        if (!cancelled) setRows(data);
      })
      .catch((e: unknown) => {
        if (!cancelled) setError(e instanceof Error ? e.message : String(e));
      });
    return () => {
      cancelled = true;
    };
  }, [year, month, accountIds]);

  if (error) {
    return (
      <div className="bg-[var(--negative)]/10 text-[var(--negative)] rounded-xl p-4">{error}</div>
    );
  }

  if (rows.length === 0) {
    return (
      <div className="bg-[var(--card)] border border-[var(--border)] rounded-xl p-6 text-center text-[var(--muted-foreground)] italic">
        {t("reports.bva.noData")}
      </div>
    );
  }

  return <BudgetVsActualTable data={rows} />;
}
