"use client";

import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useTranslations, useLocale } from "next-intl";
import { apiGet, apiPost } from "@/lib/api/client";
import type { QueueBoard } from "@/lib/api/types";
import { formatNumber } from "@/lib/format";
import { Button } from "@/components/ui/button";
import { Link } from "@/i18n/routing";

type PosQueueBarProps = {
  cafeId: string;
  branchId: string | null;
};

export function PosQueueBar({ cafeId, branchId }: PosQueueBarProps) {
  const t = useTranslations("queue");
  const locale = useLocale();
  const numberLocale = locale === "en" ? "en-US" : "fa-IR";
  const queryClient = useQueryClient();
  const query = branchId ? `?branchId=${encodeURIComponent(branchId)}` : "";

  const { data: board } = useQuery({
    queryKey: ["queue-today", cafeId, branchId],
    queryFn: () => apiGet<QueueBoard>(`/api/cafes/${cafeId}/queue/today${query}`),
    enabled: !!cafeId,
    refetchInterval: 15_000,
  });

  const callNext = useMutation({
    mutationFn: () =>
      apiPost<QueueBoard>(`/api/cafes/${cafeId}/queue/call-next${query}`, {}),
    onSuccess: () =>
      queryClient.invalidateQueries({ queryKey: ["queue-today"] }),
  });

  return (
    <div className="flex shrink-0 flex-wrap items-center gap-2 rounded-lg border border-primary/25 bg-primary/5 px-3 py-2 text-sm">
      <span className="font-medium text-primary">{t("title")}</span>
      <span className="text-muted-foreground">
        {t("nowServing")}:{" "}
        <strong className="text-foreground tabular-nums">
          {board?.nowServing != null
            ? formatNumber(board.nowServing, numberLocale)
            : "—"}
        </strong>
      </span>
      <span className="text-muted-foreground">
        {t("lastIssued")}:{" "}
        <strong className="tabular-nums">
          {formatNumber(board?.lastIssued ?? 0, numberLocale)}
        </strong>
      </span>
      <Button
        type="button"
        size="sm"
        variant="outline"
        className="h-7 text-xs"
        disabled={callNext.isPending || (board?.waitingCount ?? 0) === 0}
        onClick={() => callNext.mutate()}
      >
        {t("callNext")}
      </Button>
      <Link
        href="/queue"
        className="text-xs text-primary underline-offset-2 hover:underline"
      >
        {t("issueNext")} →
      </Link>
    </div>
  );
}
