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;
}

export default function CompareBudgetView({ year, month }: 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)
      .then((data) => {
        if (!cancelled) setRows(data);
      })
      .catch((e: unknown) => {
        if (!cancelled) setError(e instanceof Error ? e.message : String(e));
      });
    return () => {
      cancelled = true;
    };
  }, [year, month]);

  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} />;
}
