import { useMemo } from "react";
import { Building2 } from "lucide-react";
import { useAssociation } from "@/contexts/AssociationContext";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import AccountingBudgetsPage from "@/pages/accounting/AccountingBudgetsPage";

/**
 * Budget Management mirrors the Accounting → Budgeting experience, available to
 * dashboard staff outside the admin-only Accounting area. The association
 * selector drives the global selection that AccountingBudgetsPage scopes to;
 * opening a budget routes to /dashboard/budget-management/:id (full editor).
 */
export default function BudgetManagementPage() {
  const { associations, selectedAssociation, setSelectedAssociation, loadingAssociations } =
    useAssociation() as {
      associations: { id: string; name: string }[];
      selectedAssociation: { id: string; name: string } | null;
      setSelectedAssociation: (a: { id: string; name: string } | null) => void;
      loadingAssociations: boolean;
    };

  const sorted = useMemo(
    () => [...(associations ?? [])].sort((a, b) => a.name.localeCompare(b.name)),
    [associations],
  );

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-end">
        <Select
          value={selectedAssociation?.id ?? ""}
          onValueChange={(id) => setSelectedAssociation(sorted.find((a) => a.id === id) ?? null)}
        >
          <SelectTrigger className="w-[240px]">
            <Building2 className="h-4 w-4 mr-2 text-muted-foreground" />
            <SelectValue placeholder={loadingAssociations ? "Loading…" : "Select association"} />
          </SelectTrigger>
          <SelectContent>
            {sorted.map((a) => (
              <SelectItem key={a.id} value={a.id}>{a.name}</SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>

      <AccountingBudgetsPage basePath="/dashboard/budget-management" />
    </div>
  );
}
