"use client";

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

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

export function BranchSelect({ className }: { className?: string }) {
  const t = useTranslations("branches");
  const cafeId = useAuthStore((s) => s.user?.cafeId);
  const branchId = useBranchStore((s) => s.branchId);
  const setBranchId = useBranchStore((s) => s.setBranchId);

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

  useEffect(() => {
    if (branches.length === 0) return;
    const valid = branchId && branches.some((b) => b.id === branchId);
    if (!valid) setBranchId(branches[0]!.id);
  }, [branches, branchId, setBranchId]);

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

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