"use client";

import { useQuery } from "@tanstack/react-query";
import { useTranslations } from "next-intl";
import { apiGet } from "@/lib/api/client";
import { useAuthStore } from "@/lib/stores/auth.store";

type Branch = { id: string; name: string };

type BranchFilterSelectProps = {
  value: string | null;
  onChange: (branchId: string | null) => void;
  includeAll?: boolean;
  className?: string;
};

export function BranchFilterSelect({
  value,
  onChange,
  includeAll = true,
  className,
}: BranchFilterSelectProps) {
  const t = useTranslations("tables");
  const cafeId = useAuthStore((s) => s.user?.cafeId);

  const { data: branches = [] } = useQuery({
    queryKey: ["branches", cafeId],
    queryFn: () => apiGet<Branch[]>(`/api/cafes/${cafeId}/branches`),
    enabled: !!cafeId,
  });

  if (!cafeId || branches.length === 0) return null;
  if (!includeAll && branches.length <= 1) return null;

  return (
    <select
      className={className ?? "rounded-md border border-input bg-background px-3 py-2 text-sm"}
      value={value ?? ""}
      onChange={(e) => onChange(e.target.value || null)}
      aria-label={t("branchFilter")}
    >
      {includeAll ? (
        <option value="">{t("allBranches")}</option>
      ) : null}
      {branches.map((b) => (
        <option key={b.id} value={b.id}>
          {b.name}
        </option>
      ))}
    </select>
  );
}
